Reading numbers from the user, the arithmetic operators, and the two the exam loves: // and %.
Nearly every Section C asks you to replace a fixed value with input(). And // and % keep turning up: check digits, odd or even, the middle of a list.
input() waits for the user to type, and returns what they typed as a str, even if they typed a number. To do maths with it, convert it with int() (or float()).
age = int(input("Age: "))
print("Next year you'll be", age + 1)A student writes:
age = input("Age: ")
print(age + 1)
They type 16. What happens?
| Operator | Means | Example | Result |
|---|---|---|---|
+ - * | add, subtract, multiply | 4 * 3 | 12 |
/ | divide (always a float) | 10 / 2 | 5.0 |
// | whole-number division (drop the remainder) | 17 // 5 | 3 |
% | remainder ("modulus") | 17 % 5 | 2 |
** | power | 2 ** 5 | 32 |
Useful patterns:
n % 2 == 0 is True when n is even.n % 10 is the last digit of n; n // 10 drops the last digit.len(items) // 2 is the middle position of a list.What is the value of 23 // 4?
Repeating % 10 and // 10 takes a number apart digit by digit, from the right: % 10 reads the last digit, // 10 removes it. The loop below adds up the digits of 472.
n = 472
total = 0
while n > 0:
total = total + n % 10
n = n // 10
print(total)What is the value of 23 % 4?
What is the value of 2 ** 7?
/ always gives a float: print(10 / 2) shows 5.0, not 5. A missing .0 costs the mark in predict-the-output questions.
What exactly does print(18 / 3) show?
Trace the digit loop from the lesson for n = 472. Each row shows the values after one time round the loop.
| time round | n % 10 | total | n |
|---|---|---|---|
One go at each question. Your score is shown at the end, and you can retake the quiz.
What is the value of 29 // 6?
What is the value of 29 % 6?
What exactly does print(9 / 3) show?
Which condition is True exactly when n is even?
What is the value of 2 ** 4 + 10 // 3?
Which line reads a whole number from the user so you can do maths with it?