Arithmetic operations in Python
Python gives seven arithmetic operations: addition +, subtraction -, multiplication *, division /, the whole part of a quotient //, the remainder % and the power **. For example 17 / 5 = 3.4 (always a float), 17 // 5 = 3 and 17 % 5 = 2, 2 ** 5 = 32. In an expression the power is done first, then *, /, //, % (left to right), and + and - last; brackets change the order. When writing a fraction put the numerator and the denominator in separate brackets, for example (a**2 + b**2) / (a + b); if the brackets are forgotten the result is different. To increase a variable you can write the short x += y instead of x = x + y; -=, *=, /=, //=, %=, **= work the same way. With // and % the digits of a number can be separated: for a three-digit x, x // 100 is the first digit, x // 10 % 10 is the middle digit and x % 10 is the last.
| Sign | Operation |
|---|---|
| + | addition |
| - | subtraction |
| * | multiplication |
| / | division |
| // | whole part of a quotient |
| % | remainder |
| ** | power |
A class has 25 sheets of wrapping paper and each gift needs 4. A pupil used division with remainder to find how many gifts can be wrapped and how many sheets are left. The sum was easy on paper too.
Storekeepers, packers and programmers use whole quotient and remainder to share items into groups.
Pick a number of stickers between 20 and 40 and share them equally among 6 people on paper. Write how many each person gets and how many are left over, using whole quotient and remainder.
1print(17 + 5, 17 - 5, 17 * 5, 17 / 5, 17 // 5, 17 % 5, 2 ** 5)22 12 85 3.4 3 2 32
1x = int(input()) 2a = x // 100 3b = x // 10 % 10 4c = x % 10 5print(a, b, c, a + b + c)
5 8 2 15
“Find the result”: the teacher writes 6 expressions on the board (for example 2 + 3 * 4, (2 + 3) * 4, 20 // 6, 20 % 6, 2 ** 3 ** 1, 9 / 3). Groups first work them out by hand, then check in IDLE and explain any difference.