☰ Contents · Computing

Review test and arithmetic operations

Lessons 26–27 · 2 lessons · M. R. Fayziyeva, D. M. Sayfurov, N. S. Xaytullayeva. Informatics and Information Technologies, Grade 9. “Nashriyot uyi Tasvir”, Tashkent, 2020
27

Arithmetic operations in Python

Textbook: pp. 62–64
GoalKnows the Python arithmetic operations (+, -, *, /, //, %, **) and the short forms (+=, -=, *=), writes expressions with the order of operations in mind, and separates the digits of a number with // and %.
New words
//: the whole part of a quotient (floor division) · //%: the remainder of a division · %**: raising to a power · **+=: the short form of increasing a variable, x += y means x = x + y · +=
Explanation

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.

Worked examples
Operations: print(17 + 5, 17 - 5, 17 * 5, 17 / 5, 17 // 5, 17 % 5, 2 ** 5) Result: 22 12 85 3.4 3 2 32.
Separating digits: x = int(input()) ⏎ a = x // 100 ⏎ b = x // 10 % 10 ⏎ c = x % 10 ⏎ print(a, b, c, a + b + c) If 582 is typed, 5 8 2 15 is printed.
Class activity

“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.

Practice
1
What are 29 // 4 and 29 % 4 equal to?
2
Write the expression (a² + b²) / (a + b) in Python and evaluate it for a = 2, b = 3.
3
If x = 10, what is x after x += 5, x *= 2, x -= 4?
4
Why is the result of 2 + 3 * 4 equal to 14 and not 20?