Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
Before you keep reading...
Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.
2.3. Operators and Operands¶
You can build complex expressions out of simpler ones using operators. 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:
20 + 32 5 ** 2 (5 + 9) * (15 - 7)
*, and the use of parentheses for grouping,
mean in Python what they mean in mathematics. The asterisk (
*) is the
token for multiplication, and
** is the token for exponentiation (so the second line above evaluates to 5 squared (25)).
Addition, subtraction, multiplication, and exponentiation all do what you
Remember that if we want to see the results of the computation, the program needs to specify that with the word
In Python 3, which we will be using, the division operator
/ produces a floating point result (even if the result is an integer):
2.0. If you want truncated division, which ignores the remainder, you can use the
// operator (for example,
Pay particular attention to the examples above. Note that
9//5 truncates rather than rounding, so it produces the value 1 rather than 2.
The truncated division operator,
//, also works on floating point numbers. It truncates to the nearest integer, but still produces a floating point result. Thus
7.0 // 3.0 is
The modulus operator, sometimes also called the remainder operator or integer remainder operator works on integers (and integer expressions) and yields
the remainder when the first operand is divided by the second. In Python (and many other programming languages), the
modulus operator is a percent sign (
%). The syntax is the same as for other
In the above example, 7 divided by 3 is 2 when we use integer division and there is a remainder of 1.
The modulus 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
Also, you can extract the right-most digit or digits from a number. For
x % 10 yields the right-most digit of
x (in base 10).
x % 100 yields the last two digits.
Check your understanding