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.

What will be printed when you click on the Run button in the code below?

Integer Division

You can use all the standard mathematical symbols.

What will be printed when you click on the Run button in the code below?

Note

This book is using Python 3 which returns a decimal value from an integer calculation like 1 / 3. If we had executed 1 / 3 in an older Python development environment it would have printed 0 instead. In many languages if you are only using integers in calculations (whole numbers - like 42, -328, 602939) the result will also be an integer and the factional part (part after the decimal point) is thrown away. In those environments it is important to use decimal values (like 1.0 / 2, 1 / 2.0, or 1.0 / 2.0) if you want a decimal result. If you want this kind of floor division in Python 3, use the // operator. 5 // 2 will give you 2, not 2.5.

Modulo

There are also some symbols that may be used in ways that you don’t expect.

What will be printed when you click on the Run button in the code below?

You may not be familiar with the modulo (remainder) operator %. It returns the remainder when you divide the first number by the second. You probably did this long ago when you were learning long division. 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. In fact you can check if the result of X % 2 is equal to 1 to see if X is odd and if the result of X % 2 is equal to 0 then X is even.

../_images/mod-py.png

Figure 3: Long 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.

Next Section - Summary of Expression Types