Mathematical Operations

Now that we now how to create variables, let us see which math operators Python knows about!

mathoperations.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from __future__ import print_function
from __future__ import division

a = 10
b = 27
print("a is {}, b is {}".format(a, b))

c = a + b
print("a+b is {}".format(c))
d = a - b
print("a-b is {}".format(d))
e = a+b*3
print("a+b*3 is {}".format(e))
print()

f = b / 2
print("b/2 is {}".format(f))
g = b // 2
print("b//2 is {}".format(g))
h = b % 10
print("b%10 is {}".format(h))
print("2**7 is {}".format(2**7))
print()

w = 1.1
print("\nx is {}".format(w))
x = w*w
print("w*w is {}".format(x))
y = b / 2
print("b/2 is {}".format(y))
z = b // 2
print("b//2 is {}".format(z))
print()

one = "dog"
two = "house"
both = one + two
print(both)

What You Should See

a is 10, b is 27
a+b is 37
a-b is -17
a+b*3 is 91

b/2 is 13.5
b//2 is 13
b%10 is 7
2**7 is 128


x is 1.1
w*w is 1.21
b/2 is 13.5
b//2 is 13

doghouse

Most of this should be pretty expected. The plus sign (+) means addition and the minus sign (-) means subtraction. Python uses the asterisk (*) for multiplication and knows about the order of operations.

Python has two types of division. The first (line 16) is normal division, which uses the slash (/).

The second uses two slashes (//), which performs so-called "integer" division. The result of integer division has no decimals and rounds toward negative infinity.

In Python 2, this was different. The single slash division was integer division, and the double-slash division didn't exist. To get floating point, division, you would have had to do something like f = b / 2.0 or even f = float(a) / b.

The Python 3 way is a little friendlier to beginners, because regular division works more like you would expect. Since we're using Python 2, we import the new style of division from the future.

The percent sign (%) is called modulus and it gives you the remainder from a division. So 10%3 gives you 1: the remainder of 10 divided by 3.

Two asterisks in a row (**) is the exponent operator, so 4**2 is 16.

Finally line 37 shows that two strings can be stuck together using the plus sign. This is usually called "concatenation".

Study Drills

  1. Add two new variables to the program (ints, floats or one of each). Put values into the new variables using numbers and operators. Then display them on the screen. (Do all this below line 38.)



©2017 Graham Mitchell