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.
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.
3 + 6
We can also perform subtraction in Python.
7.5 - 4.2
We will now consider the operations of multiplcation and division. Multiplication is performed using the *
operator, as shown below.
6 * 7
Division can be performed using the /
operator.
5 / 2
Attempting to divide by zero will result in an error.
42 / 0
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$.
# Exponentiation
3 ** 4
Python recognizes the standard order of operations.
4 + 5 * 6
Parentheses can be used to form more complex arithmetic expressions.
# Parentheses and Order of operations
7 * (3 + 8/4)
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.
8 % 3
25 % 7
90 % 3
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.
We define variables using the assignment operator "=".
# Define variables x and y
x = 4
y = 9
We can use the print()
to check the value of the variables x
and y
.
print(x)
print(y)
We can perform arithmetic operations using variables that are storing numbers.
print(3*x)
print(x + 2*y)
Notice using variables in arithmetic operations does not affect the values of those variables.
print(x)
print(y)
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
.
z = x*y
Print the value of z
.
print(z)
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.
n = 42
print(n)
n = 2.3
print(n)
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
.
a = 37
b = a
print(a)
print(b)
We now change the value of b
to 18 and then print a
and b
again.
b = 18
print(a)
print(b)
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.
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.
# Define a variable s with initial value of 7
s = 7
print(s)
# Double the value of s, storing the result back into s.
s = 2*s
print(s)
# Increment the value of s by 3.
s = s + 3
print(s)
# Square the value of s.
s = s**2
print(s)
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)
# Increment i by 1.
#i = i + 1
i += 1
print(i)
# Increment i by 3.
i += 3
print(i)
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
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.
# Variable must start with a letter.
1var = 3.14159
# Variable names cannot contain spaces.
bad name = 2.71828
# Underscores are the only non-alphanumeric characters allowed in a name.
thi$_is_inv@lid = 1.414
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.
# 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.
print(var)
print(Var)
print(vAr)
# The variable VAR is currently undefined.
print(VAR)
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).
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.
int
variable is used to represent an integer. 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)
y = 3.7
type(y)
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.
z = 14.0
type(z)
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))
print(x)
print(z)
v = x + z
print(v)
print(type(v))
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))
c = 20
d = 4
p = c / d
print(p)
print(type(p))
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.
p = 4
print(type(p))
p = 3.999
print(type(p))
q = 7
print(type(q))
q = 7 / 1
print(type(q))
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.
# Coercing an int to a float.
x_int = 19
x_float = float(x_int)
print(x_float)
print(type(x_float))
# Coercing a float to an int.
y_float = 6.8
y_int = int(y_float)
print(y_int)
print(type(y_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.
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.
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))
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.
print(round(12.3))
print(round(12.7))
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.
empty_var = None
print(empty_var)
print(type(empty_var))
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
.
my_output = print('Hello')
print(my_output)
We will discuss return values of functions and the None
value further in later lessons.