Section 2.7 Operators and Operands
Operators are special tokens that represent computations like addition, multiplication and division. The values the operator works on are called operands.
The following are all legal Python expressions whose meaning is more or less clear:
20 + 32
hour - 1
hour * 60 + minute
minute / 60
5 ** 2
(5 + 9) * (15 - 7)
Python uses special characters
called operators
that perform the following operations:
There are several other operators that we will learn in future chapters. But these are the ones that you’re going to need more or less all of your assignments!
The first six operators have functionality that you’re most probably pretty familiar with! On the other hand, we have two more operators that are used frequently in programming but not that much in math classes. These are integer division, and modulo.
In the previous example 5 / 3
resulted 1.66666666
. This is because /
always returns a floating point result. However, in certain situations, we need an integer result from division. Integer division, or the //
operator, divides the number, but rounds it down to the nearest integer. So for the previous example, 5 // 3
will result 1
The modulo operator, %
yields the remainder when the first operand is divided by the second (that’s why you can also remember it as remainder operator). For example, 5 % 3
will result 2
as 5 = 3 * 1 + 2
.
When a variable name appears in place of an operand, python substitutes that variable name with its assigned value. For example, what if we wanted to convert 645 minutes into hours?
The modulo operator turns out to be surprisingly useful. For example, you can check whether one number is divisible by another—if x % y
is zero, then x
is divisible by y
. Also, you can extract the right-most digit or digits from a number. For example, x % 10
yields the right-most digit of x
(in base 10). Similarly x % 100
yields the last two digits.
The remainder operator is extremely useful for doing conversions, say from seconds, to hours, minutes and seconds. If we start with a number of seconds, say 7684, the following program uses integer division and remainder to convert to an easier form. Step through it to be sure you understand how the division and remainder operators are being used to compute the correct values.
Check your understanding
Checkpoint 2.7.1.
Checkpoint 2.7.2.
Checkpoint 2.7.3.
You have attempted
of
activities on this page.