Lesson 01 - Arithmetic and Variables

The following topics are discussed in this notebook:

  • Arithmetic operations in Python.
  • Defining and using variables.
  • Variable names.
  • Variable types.

Additional Resources

Arithmetic operations

Python has the capability to perform calculations involving addition, subtraction, multiplication, and division. These basic arithmetic operations are some of the simplest types of commands that Python is able to process.

In [1]:
# Addition
3 + 6
Out[1]:
9
In [2]:
# Multiplication
6 * 7
Out[2]:
42
In [3]:
# Division
5 / 2
Out[3]:
2.5
In [4]:
# Division
7 / 3
Out[4]:
2.3333333333333335

Do you notice anything unusual about the output of the next line?

In [5]:
8 / 2
Out[5]:
4.0

Attempting to divide by zero will result in an error.

In [6]:
42 / 0
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-6-52cebea8b64f> in <module>()
----> 1 42 / 0

ZeroDivisionError: division by zero

Python uses the symbol ** to indicate the operation of exponentiation.

In [7]:
# Exponentiation
3 ** 4
Out[7]:
81

Python recognizes the standard order of operations.

In [8]:
4 + 5 * 6
Out[8]:
34

Parentheses can be used to form more complex arithmetic expressions.

In [9]:
# Parentheses and Order of operations
5 * (3 + 8 / 2)
Out[9]:
35.0

Introduction to Variables

Variables are an important aspect of any programming language. A variable can be thought of as a container or storage location for a piece of information. Every variable has two features:

  • A 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 name, which is used to refer to the variable. We use the name of a variable to access its contents.

We define variables using the assignment operator "=".

In [10]:
# Define variables x and y
x = 4
y = 9

We can call the variable x to check its value.

In [11]:
x
Out[11]:
4

Now let's check the value of y.

In [12]:
y
Out[12]:
9

As we have seen, it is possible to have multiple lines of code within a single Jupyter cell. However, if we have multiple lines that all generate some sort of output, only the last of these lines will have its output displayed.

In [13]:
x
y
Out[13]:
9

To display the value of more than one variable in a single Jupyter notebook cell, we need to use the print() function.

In [14]:
print(x)
print(y)
4
9

We can perform arithmetic operations using variables that are storing numbers.

In [15]:
print(x + y)   # Sum of x and y
print(x * y)   # Product of x and y
13
36

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

In [16]:
print(x)
print(y)
4
9
In [17]:
print(2 * x)
print(x - y)
8
-5
In [18]:
print(x)
print(y)
4
9

Calculate the product of x and y, and store the result in a new variable, z.

In [19]:
z = x * y

Print the value of z.

In [20]:
z
Out[20]:
36

Redefining variables

In general, variables are not static objects. While the name of a variable is fixed, the contents of that variable can be changed or overwritten. We illustrate this idea in the next two code cells.

In the next cell, we:

  • set the value of a to 37,
  • create a new variable b, which is equalto a, and
  • print the values of a and b.
In [21]:
a = 37
b = a
print(a)
print(b)
37
37

We now change the value of b to 18 and then print a and b again.

In [22]:
b = 18
print(a)
print(b)
37
18

Notice that the value of b changed, but the value of a was unaffected. Although b was set equal to a when it was created, it is a separate variable.

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.

In [23]:
# Define a variable s with initial value of 7
s = 7
print(s)
7
In [24]:
# Double the value of s, storing the result back into s.
s = s * 2
print(s)
14
In [25]:
# Increment the value of s by 3.
s = s + 3
print(s)
17
In [26]:
# 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.

In [27]:
# Define i to have an initial value of 5.
i = 5
print(i)
5
In [28]:
# Increment i by 1.
i += 1
print(i)
6
In [29]:
# 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.

In [30]:
# These are valid variable names.

var1 = 3.14159
this_is_a_valid_name = 2.71828
t0tally_val1d = 1.414
In [31]:
# Variable must start with a letter.
1var = 3.14159
  File "<ipython-input-31-ca98c4cf8759>", line 2
    1var = 3.14159
       ^
SyntaxError: invalid syntax
In [32]:
# Variable names cannot contain spaces.
bad name = 2.71828
  File "<ipython-input-32-c226f65a4995>", line 2
    bad name = 2.71828
           ^
SyntaxError: invalid syntax
In [33]:
# 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.

In [34]:
# var, Var, and vAr all refer to different variables.
var = 12
Var = 45
vAr = 139
In [35]:
print(var)
print(Var)
print(vAr)
12
45
139
In [36]:
# 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

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.

In [37]:
x = 7
type(x)
Out[37]:
int
In [38]:
y = 3.7
type(y)
Out[38]:
float

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

In [39]:
z = 14.0
type(z)
Out[39]:
float

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

In [40]:
print(x)
print(y)
u = x + y
print(u)
print(type(u))
7
3.7
10.7
<class 'float'>
In [41]:
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.

In [42]:
a = 7
b = 5
q = a / b
print(q)
print(type(q))
1.4
<class 'float'>
In [43]:
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.

In [44]:
p = 4
print(type(p))
p = 3.999
print(type(p))
<class 'int'>
<class 'float'>
In [45]:
q = 7
print(type(q))
q = 7 / 1
print(type(q))
<class 'int'>
<class 'float'>