Lesson 04 - Arithmetic and Variables

The following topics are discussed in this notebook:

  • Arithmetic operations in Python.
  • Defining and using variables.
  • Changing the value of variables.
  • Variable names.
  • Numeric data types.

Arithmetic Operations

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

Addition and Subtraction

We will begin our discussion of mathematical operations with addition and subtraction. In the celll below, we provide an example of using Python to perform addition.

In [1]:
3 + 6
Out[1]:
9

We can also perform subtraction in Python.

In [2]:
7.5 - 4.2
Out[2]:
3.3

Multiplication and Division

We will now consider the operations of multiplcation and division. Multiplication is performed using the * operator, as shown below.

In [3]:
6 * 7
Out[3]:
42

Division can be performed using the / operator.

In [4]:
5 / 2
Out[4]:
2.5

Attempting to divide by zero will result in an error.

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

ZeroDivisionError: division by zero

Exponentiation

Python uses two asterisks, ** to indicate the operation of exponentiation. In the next cell, we will calculate 3 raised to the 4th power, or $3^4$.

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

Order of Operations

Python recognizes the standard order of operations.

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

Parentheses can be used to form more complex arithmetic expressions.

In [8]:
# Parentheses and Order of operations
7 * (3 + 8/4)
Out[8]:
35.0

The Modulus Operator

Python, like most programming languages, provides the ability to perform the modulus operation. This operation provides the remainder that would result from dividing one integer by another. In Python, this is performed by playing the % symbol between two integers. The number on the left is the dividend and the one on the right is the divisor. We provide several examples below.

In [9]:
8 % 3
Out[9]:
2
In [10]:
25 % 7
Out[10]:
4
In [11]:
90 % 3
Out[11]:
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 value and a name.

  • The value of a variable is the information that 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.
  • The name of a variable is sequence of characters that is used to identify the variable. We use the name of a variable in statements to access its contents.

We define variables using the assignment operator "=".

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

We can use the print() to check the value of the variables x and y.

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

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

In [14]:
print(3*x)
print(x + 2*y)
12
22

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

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

We can use previously defined variables to create new variables.

In the cell below, we calculate the product of x and y, and store the result in a new variable, z.

In [16]:
z = x*y

Print the value of z.

In [17]:
print(z)
36

Changing the Value of a Variable

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 [18]:
n = 42
print(n)
42
In [19]:
n = 2.3
print(n)
2.3

For variables that contain numeric data, if we create a variable by setting its value equal to a previously created variable, this will result in a the creation of a completely new variable. The two variables will have the same value (at least initially), but will be distinct from one another.

n the next cell, we create a new variable called a with a value of 37. We then create a variable b, setting it equal to a.

In [20]:
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 [21]:
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.

Assigning a Value to a Variable Based on its Current Value

Occasionally we will want to redefine the value of a variable in a way that depends on the current value of the variable. The next few cells provide several examples of this. In each case, the expression on the right side of the assignment operator = is evaluated numerically, and then the resulting numerical value is assigned to the variable.

In [22]:
# Define a variable s with initial value of 7
s = 7
print(s)
7
In [23]:
# Double the value of s, storing the result back into s.
s = 2*s
print(s)
14
In [24]:
# Increment the value of s by 3.
s = s + 3
print(s)
17
In [25]:
# 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 [26]:
# Define i to have an initial value of 5.
i = 5
print(i)
5
In [27]:
# Increment i by 1.
#i = i + 1
i += 1
print(i)
6
In [28]:
# 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 [29]:
# These are valid variable names.

var1 = 3.14159
this_is_a_valid_name = 2.71828
t0tally_val1d = 1.414

Although the variable name t0tally_val1d is allowed by Python, using a variable name like this should be discouraged. Naming variables in a way that can make them difficult to read or remember can cause headaches for yourself, or for those reading your code.

The next three cells illustrate variable names that are not valid.

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

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

In [42]:
# var, Var, and vAr all refer to different variables.
var = 12
Var = 45
vAr = 139

Let's print the value of these variables to demonstrate that they are distinct objects.

In [43]:
print(var)
print(Var)
print(vAr)
12
45
139
In [44]:
# The variable VAR is currently undefined. 
print(VAR)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-44-8cebca2ac97f> in <module>
      1 # The variable VAR is currently undefined.
----> 2 print(VAR)

NameError: name 'VAR' is not defined

Although Python allows you to use var, Var, and vAr as names for distinct variables, this is bad programming practice as it could cause confusion for anyone reading or working with your code (including yourself).

Numeric Data Types

Every variable in Python has a "type". The type of a variable is based on the contents of that variable, and determines the ways in which that variable can be used. For example, we cannot perform certain operations on variables of certain types.

We will begin our discussion of data types with the data types intended to hold numbers. Python has three numerical variable types: int, float, and complex. In this class, we will work only with the int and float variables.

  • 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 [45]:
x = 7
type(x)
Out[45]:
int
In [46]:
y = 3.7
type(y)
Out[46]:
float

Python infers whether a numeric variable should be stored as an int or a float based on the value of that variable. Occasionally we might wish to assign a whole number value to a variable, but have it actually stored as a float. We can accomplish this by adding ".0" to the end of the number.

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

Operations Combining Floats and Ints

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

In [48]:
print(x)
print(y)
u = x + y
print(u)
print(type(u))
7
3.7
10.7
<class 'float'>
In [49]:
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 [50]:
a = 7
b = 5
q = a / b
print(q)
print(type(q))
1.4
<class 'float'>
In [51]:
c = 20
d = 4
p = c / d
print(p)
print(type(p))
5.0
<class 'float'>

Static vs. Dynamic Typing

In many programming languages, you specify a type for a variable upon creation. In those languages, you can change the value of the variable, but the new value must be consistent with the specified type of the variable. Languages with this property are referred to as being statically typed.

Python is a dynamically typed language. In such a language, we do not specify the type of a variable when we create it. We specify only a value, and Python infers the data type from that value. If we change the value of the variable in a way that is inconsistent with the current type of the variable, then Python simply changes the variable's type.

Dynamic typing is demonstrated in the two cells below.

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

Type Coercion

There are occasions when we would like to convert a variable from one data type to another. This is referred to as type coercion. We can coerce a variable to another date type by passing it to a function whose name is identical to the desired data type. For instance, if we want to convert a variable x to an integer, we would use the command int(x). If we want to convert a variable y to a float, we would wuse float(y).

We will study coercion more later, but for now, let's see what happens when we coerce ints to floats and vice-versa.

In [54]:
# Coercing an int to a float. 

x_int = 19
x_float = float(x_int)

print(x_float)
print(type(x_float))
19.0
<class 'float'>
In [55]:
# Coercing a float to an int. 

y_float = 6.8
y_int = int(y_float)

print(y_int)
print(type(y_int))
6
<class 'int'>

Notice that we we coerce a float to an int, the Python does not round the float to the nearest integer. Instead, it truncates (or chops off) the decimal portion of the number. In other words, when performing float-to-int coercion, Python will ALWAYS round the number DOWN to the next lowest integer, regardless of the value of the decimal portion.

Rounding

If we wish to round a float value, we can do so using the round() function. The syntax for round() is as follows: If we wish to round the value number to a number of decimal places indicated by digits, we could use the command round(number, digits).

Some examples of the round() function are provided below.

In [56]:
print(round(3.14159, 0))
print(round(3.14159, 1))
print(round(3.14159, 2))
print(round(3.14159, 3))
print(round(3.14159, 4))
3.0
3.1
3.14
3.142
3.1416

If we do not provide round() with the desired number of digits, writing only round(number), then Python will round the number to the nearest integer.

In [57]:
print(round(12.3))
print(round(12.7))
12
13

The None Type

Python provides a special value called None that is used to indicate the absense of a value. In the cell below, we create a variable storing a value of None. We then print this variable, as well as its type.

In [58]:
empty_var = None
print(empty_var)
print(type(empty_var))
None
<class 'NoneType'>

One situation in which you might encounter None is if you attempt to assign to a variable the output (or return value) of a function that does not actually produce any output. The print() function, for example, performs an action by displaying text to the screen, but does not actually return any values. We see this in the next cell, in which we attempt to store the output of print() into a variable, and then print the value of this variable to confirm that is is None.

In [59]:
my_output = print('Hello')
print(my_output)
Hello
None

We will discuss return values of functions and the None value further in later lessons.