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 Variables

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 demonstrated in the callout below.

Concept: Defining a Variable

The pseudocode code below illustrates how to define a variable with a specific name and value.

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 in the variable must appear on the right.

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

x = 4
y = 9

After running the cell above, we will have two variables named x and y stored in memory for the duration of our Python session. Any time we reference the names of either of these variables, Python will substitute in the value contained in the variable.

We can use the print() function to confirm that the values stored in x and y are as expected.

print(x)
print(y)
4
9

Using Variables in Arithmetic Expressions

We can perform arithmetic operations using variables that we have previously created. Suppose that we have created two variables x and y as shown below.

x = 4
y = 9

We will now print the value of 2 times x and the value of x minus y.

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

We can also use previously defined variables in an expression for the value when defining a 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

Note

Note that the code in the cell above simply sets the value of the variabe z to 36. It does NOT establish a relationship between the variables x, y, and z. As we will see later, the value stored in a variable can be changed. If we were to change the value of either x or y, that would have no effect on the value of z.

Using variables in arithmetic operations does not affect the values of those variables. We will confirm this by printing the values of x and y.

print(x)
print(y)
4
9

Changing Variable Values

We can change the value of a previously created variable by simply assigning a new value to it. This is demonstrated in the cell below.

a = 2 * 6 + 1
print(a)

a = 3 * 5 / 2
print(a)
13
7.5

Self-Referential Variable Definitions

We have seen that using a variable in an arithmetic operation does not affect the value of that variable. To illustrate this point, in the cell below, we will create a variable k and multiply it by 2 to create a new variable c. We will then use print() to confirm that the value of k has not been changed.

k = 7
c = 2*k

print(k)
print(c)
7
14

But what if we actually did want to double the value stored in the variable k? It is also possible to reassign the value of a variable in such a way that its new value depends upon its previous value. In order to accomplish this, you would use the assignment operator = to redefine the variable, and you would use an expression involving the variable itself on the right side of the assignment operator.

We demonstrate this in the cell below by creating a variable k and then doubling the value stored in k.

k = 7
print(k)

k = 2 * k
print(k)
7
14

Incrementing Variables

One of the most commonly encountered ways of updating the value of a variable is to increase it by a fixed amount. This process is know as incrementation.

In the cell below, we define a variable n to be equal to 5 and we then increment its value by 3.

n = 5
print(n)

n = n + 3
print(n)
5
8

As you will see in examples presented later in the material, the most common number to increment a variable by is 1. In the cell below, we further increment n by increasing it by 1 a few times.

n = n + 1
print(n)

n = n + 1
print(n)

n = n + 1
print(n)
9
10
11

Incrementation has many practical applications in programming. It is used frequently enough that Python (as well as most other programming languages) has offered a shortcut for performing this task. Specifically, the “plus-equals” operator += can be used to increment a variable by a certain amount. The callout below demonstrates the syntax for using this operator.

Concept: Incrementation

The two lines of code presented below are equivalent. Each line will result in the variable x being incremented by the value stored in k.

x = x + k
x += k

We will now demonstrate the use of the += operator by defining a variable and then incrementing it by 1 a few times.

i = 5        # Set initial value of i to 5. 
print(i)

i += 1       # Increment i by 1.
print(i)

i += 1       # Increment i by 1.
print(i)

i += 1       # Increment i by 1.
print(i)
5
6
7
8

Variable Names

Up to this point, we have used simple, one-letter names for our variables. Python allows to to create longer, more descriptive names for variables. There are a few rules that need to be followed when naming a variable, however. These are described in the callout below.

Concept: Rules for Variable Names

A variable name in Python can be set to any sequence of characters that following rules:

  • Variable names can include numbers, letters (uppercase or lowercase), and underscores.

  • Variable names cannot contain spaces or any characters not mentioned above.

  • Variable names must always start with a letter or underscore.

In the cell below, we provide a few examples of valid variable names.

var1 = 42
var2 = 37
this_is_a_valid_name = 2.71828
myVariable = 3.14159

Each of the lines of code below illustrates an attempt to define a variable using an invalid variable name. In each case, determine which rule was violated.

1var = 7
my variable = 3
thi$_is_inv@lid = 19

Attempting to run any of the lines of code shown above would result in the following error: SyntaxError: invalid syntax

Case Sensitivity

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. For example, the three lines of code in the cell below will create three separate variables.

var = 12
Var = 45
vAr = 139

To confirm that the variables var, Var, and vAr are distinct, we will now print their values.

print(var)
print(Var)
print(vAr)
12
45
139

PEP 8 Standards for Variable Names

While Python allows for a wide range of variable names, certain naming formats should be avoided for the sake of readability. Python community has developed a set of conventions and guidelines for writing Python code known as the PEP 8 Style Guide. This style guide covers a wide range of topics, including variable names. The PEP 8 standards adopt the following conventions for variable names:

  • Variable names should not include uppercase letters.

  • Variable names can be single letters, or can consist of multiple words.

  • Different words in a variable name should be separated with underscores.

  • Descriptive variable names are generally preferred.

Keep in mind that the PEP 8 guidelines are conventions and not rules of the language itself. Violating these conventions will not results in errors, and there are occasions when it might make sense to name a variable in a way that violates these standards. However, it is a good idea for a Python programmer to be aware of the PEP 8 guidelines and to adhere to them when possible.

You can learn more about the PEP 8 guidelines here: How to write Beautiful Python Code with PEP 8. The complete PEP 8 Style Guide can be found on the python.org site: PEP 8 Style Guide

Data Types

Every value in Python has a data type that describes what kind of information is represented by the value. There are many different types that a value can have, but the three most basic types in Python are integers, floating-point numbers (or floats), and strings.

  • An integer, or int, is a value that represents a whole number. For example: 7, 42, and 1337.

  • A float is a value that represents a decimal number. For example, 0.33, 3.14, and 25.1.

  • A string is a value that represents a piece of text. For example: 'cat', 'Python', and 'Hello World!'.

Every variable also has a data type determined by the value stored inside it. We can use the type() function to check the type of a variable. This is demonstrated below.

x = 17
y = 4.3
z = 'blah'

print('The type of x is:', type(x))
print('The type of y is:', type(y))
print('The type of z is:', type(z))
The type of x is: <class 'int'>
The type of y is: <class 'float'>
The type of z is: <class 'str'>

Data Types and Operations

The data type for a value determines the ways that the value can be used in operations. For example, since float and int are both numeric data types, Python allows use to add values of this type. On the other hand, if we try to add an int value and a str value, we will get an error.

We demonstrate the addition of a float and an int in the cell below.

x = 17
y = 4.3

u = x + y

print(u)
print(type(u))
21.3
<class 'float'>

We will now demonstrate that adding an int to a str will result in an error.

x = 17
y = "seventeen"

w = x + y
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-18-35cd780ac07a> in <module>
      2 y = "seventeen"
      3 
----> 4 w = x + y

TypeError: unsupported operand type(s) for +: 'int' and 'str'

Notice that the error above is classified as a TypeError. This tells us that we are trying to use one or more values in a way that is not allowed based on their types. The error message goes on to tell us that the addition operator + is not supported between values of type int and str. It is important to be able to interpret error messages like this since they can help you to identify the source of an error. You can find more information about error messages in the Error Messages page in the glossary.

We will discuss data types in more detail in the next few chapters.