Introduction to Variables

A variable can be thought of as a container or storage location for a piece of information. Every variable in Python consists of two features: a name and a value.

  • A variable’s value refers to the piece of information which is stored within the variable. This could be a single number, a list of numbers, a string of characters, or some more complex type of information.

  • A variable’s name is used to refer to the variable. We use the name of a variable to access its contents.

In the first section of this chapter, we will discuss how to define a variable.

Defining a Variable

We define new variables in Python using the assignment operator, which is denoted using a single equals sign (=). The syntax for using the assignment operator is as follows:

Name = Value

Note that the name of the new variable must always appear on the left side of the assignment operator and the value to be stored must appear on the right.

In the cell below, we define two new variables, x and y.

Defining a Variable

We define new variables in Python using the assignment operator, which is represented by a single equals sign (=). The syntax for using the assignment operator is as follows:

Name = Value

Concept: Defining a Variable

You define a variable using the assignment operation, =. The syntax is demonstrated below.

Name = Value

Blah blah blah.

Note that the name of the new variable must always appear on the left side of the assignment operator and the value to be stored must appear on the right.

In the cell below, we define two new variables, x and y.

x = 4
y = 9

We can print the variable x to check its value.

print(x)
4

Now let’s check the value of y.

print(y)
9

Using Variables in Arithmetic Expressions

We can perform arithmetic operations using variables that we have previously created.

print(2 * x)
print(x - y)
8
-5

Notice using variables in arithmetic operations does not affect the values of those variables.

print(x)
print(y)
4
9

When defining a variable, we can use previously created variableswithin the expression used to set the value of the new variable.

In the cell below, we create a new variable z and set it equal to the product of x and y.

z = x * y

print(z)
36

Reassigning Values to Variables

We can change the value of a previously created variable by simply assigning a new value to it. Before demonstrating some examples, we will first create three new variables named a, b, and c,

a = 5
b = 7
c = 2 * a + b

We will print the value of c to confirm that it is 17.

print(c)
17

Variable Reassignment

In the cell below, we will change the value of the variable a from 5 to 11. We will then print a to confirm that the value of the variable has been updated.

a = 11
print(a)
11

We will now print the value of c to show that changing the value of a does not change the value of c, even though c was defined using a.

print(c)
17

The statement c = 2 * a + b uses a and b to determine the value that was to be stored in c, which was 17. It does not define a permanent relationship between the variales a, b, and c.

Setting a Variable Equal to Another

On occasion, we might wish to set one variable equal to another. What the exact results of such an operation depend on what types of values are stored in the variables, but for now, let’s focus on variables containing simple numeric values. In this case, the value of the new variable is set to be equal to the value of the old variable, but the two variables are not linked in any way after the value is assigned.

To illustrate this, in the cell below, we define a variable u, and we then set v equal to x. We then print both values to confirm that they are the same.

u = 13.7
v = u

print(u)
print(v)
13.7
13.7

To confirm that the two variables are not connected, we will change the value of u and will then print both variables again.

u = 52.8

print(u)
print(v)
52.8
13.7

The value of u was changed, but the value of v was unaffected.

As indicated above, there are situations where setting one variable equal to another produces a different kind of behavior. In particular, when we discuss lists, we will see that setting a variable equal to another variable that contains a list will result in the two variables referring to the exact same list.

Redefining a variable using its current value.

In the example above, we overwrote the value of the variable b with a new value that was completely unrelated to its original value. It is also possible to reassign the value of a variable in such a way that its new value depends upon its previous value.

# Define a variable s with initial value of 7
s = 7
print(s)
7
# Double the value of s, storing the result back into s.
s = s * 2
print(s)
14
# Increment the value of s by 3.
s = s + 3
print(s)
17
# Square the value of s. 
s = s ** 2
print(s)
289

Incrementing Variables

The process of incrementing, or increasing, a variable by a certain amount is one with many practical applications in computer science and data science. Python, like many other programming languages, comes equipped with a shorthand means of performing this task.

The operator “+=” is used to perform variable incrementation, as shown below.

# Define i to have an initial value of 5.
i = 5
print(i)
5
# Increment i by 1.
i += 1
print(i)
6
# Increment i by 3.
i += 3
print(i)
9

Variable Names

Python variable names can include numbers, letters, and underscores, but cannot contain any other characters or spaces. Variable names must always start with a letter.

# These are valid variable names.

var1 = 3.14159
this_is_a_valid_name = 2.71828
t0tally_val1d = 1.414
# Variable must start with a letter.
1var = 3.14159
  File "<ipython-input-21-ca98c4cf8759>", line 2
    1var = 3.14159
       ^
SyntaxError: invalid syntax
# Variable names cannot contain spaces.
bad name = 2.71828
  File "<ipython-input-32-c226f65a4995>", line 2
    bad name = 2.71828
           ^
SyntaxError: invalid syntax
# Underscores are the only non-alphanumeric characters allowed in a name.
thi$_is_inv@lid = 1.414
  File "<ipython-input-33-66da23651f39>", line 2
    thi$_is_inv@lid = 1.414
       ^
SyntaxError: invalid syntax

Python variable names are case sensitive. Variable names that use different cominations of uppercase and lowercase letters, but are otherwise identical will refer to different variables.

# var, Var, and vAr all refer to different variables.
var = 12
Var = 45
vAr = 139
print(var)
print(Var)
print(vAr)
12
45
139
# The variable VAR is currently undefined. 
print(VAR)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-36-8cebca2ac97f> in <module>()
      1 # The variable VAR is currently undefined.
----> 2 print(VAR)

NameError: name 'VAR' is not defined

Warning

  • Mention PEP8 Standards

Variable Types

Every variable in Python has a “type”. The type of a variable determines the ways in which we can use the variable.

Python has four numerical variable types: int, long, float, and complex. For now, we will focus on int and float.

  • An int variable is used to represent an integer.

  • A float variable is used to represent a decimal number.

We will discuss the importance of variable types in more depth later. For now, we will show how to determine a variable’s type using the type() function.

x = 7
type(x)
int
y = 3.7
type(y)
float

We can coerce an integer value to be stored as a float by adding “.0” to the end of the number.

z = 14.0
type(z)
float

The sum of an int and a float is always stored as a float.

print(x)
print(y)
u = x + y
print(u)
print(type(u))
7
3.7
10.7
<class 'float'>
print(x)
print(z)
v = x + z
print(v)
print(type(v))
7
14.0
21.0
<class 'float'>

The ratio of any combination of ints and floats is always stored as a float.

a = 7
b = 5
q = a / b
print(q)
print(type(q))
1.4
<class 'float'>
c = 20
d = 4
p = c / d
print(p)
print(type(p))
5.0
<class 'float'>

It is possible to change the type of a variable in Python. This is not allowed in many other programming languages.

p = 4
print(type(p))
p = 3.999
print(type(p))
<class 'int'>
<class 'float'>
q = 7
print(type(q))
q = 7 / 1
print(type(q))
<class 'int'>
<class 'float'>