2.3. Expressions

The right hand side of the assignment statement doesn’t have to be a value. It can be an arithmetic expression, like 2 * 2. The expression will be evaluated and the result from the expression will be stored in the variable.

2.3.1. Operations

You can use all the standard mathematical operations, you just have to know the right symbols to use: / means divsion; * means times; ** means “to the power of”.

2.3.2. Division and Integer Division

This book is using Python 3 which returns a decimal value - 1.66666666666667 - from a calculation like 5 / 3. If we executed 5 / 3 in many programming languages (or older version so Python) it would result in just 1 because we can only divide 5 by 3 one whole time. This form of division is known as integer division and is what you probably learned in elementary school before you learned long division.

There are times when we want to do integer division as part of solving a problem. If I want to figure out how many whole feet are in 37 inches, I would divide 37 by 12. From it, I want an answer of just 3, not 3.083333333333333. To do integer division in Python, we use //. Compare the two results in the code sample below. The first is done using normal (decimal) division. The second is from doing integer division:

Note

Integer division always just ignores the remainder - it does not round the answer. 5 // 3 is just 1.

2.3.3. Modulo

If you are doing integer division, you may also care about the remainder. When I divide do 37/12 to figure out the number of feet in 37 inches, I get 3. But maybe I also want to know that there is one inch left over.

You may not be familiar with the modulo (remainder) operator %. It returns the remainder when you divide the first number by the second. In the case of 4 % 2, 2 goes into 4 two times with a remainder of 0. The result of 5 % 2 would be 1 since 2 goes into 5, two times with a remainder of 1.

../_images/mod-py.png

Division showing the whole number result and the remainder

Note

The result of x % y when x is smaller than y is always x. The value y can’t go into x at all, since x is smaller than y, so the result is just x. So if you see 2 % 3 the result is 2. Edit the code above to try this for yourself. Change the code to result = 2 % 3 and see what that prints when it is run.

You have attempted of activities on this page