Arithmetic
print(17 + 5) print(17 - 5) print(17 * 5) print(17 / 5) print(17 // 5) print(17 % 5) print(2 ** 10)
Write Python. Understand every error.
Python basics · topic 5 of 25
Arithmetic operators work on numbers:
+ add, - subtract, * multiply/ divide, which always gives a float: 7 / 2 is 3.5// floor division, the whole-number part: 7 // 2 is 3% remainder: 7 % 2 is 1** power: 2 ** 5 is 32Python follows the usual order: brackets first, then **, then *, /, //, %, and finally + and -.
Comparison operators give True or False: == equal, != not equal, <, >, <=, >=. Logical operators combine them: and needs both sides true, or needs at least one, and not flips the result.
marks = 72 print(marks >= 40 and marks < 75)
/ always gives a float, // gives the whole-number part and % gives the remainder: 7 / 2 is 3.5, 7 // 2 is 3 and 7 % 2 is 1.** is the power operator: 2 ** 5 is 32.True or False, and and, or and not combine them.^ for power. In Python ^ is a different operator, so write **./ gives a decimal even when the answer is whole: 10 / 5 is 2.0.
print(17 + 5) print(17 - 5) print(17 * 5) print(17 / 5) print(17 // 5) print(17 % 5) print(2 ** 10)
sweets = 23 friends = 4 print("Each friend gets", sweets // friends) print("Left over:", sweets % friends)
print(10 > 3) print(10 == 3) print(10 != 3) print("abc" == "abc")
age = 20 has_id = True print(age >= 18 and has_id) print(age < 13 or age > 60) print(not has_id)
5 quick questions to check your understanding. Choose an answer for each, then press Check answers.
print(17 // 5, 17 % 5)
// gives the whole-number part of the division and % gives the remainder.
print(10 / 4)
/ always gives a float result.
print(2 ** 3 ** 2)
** works right to left: 3 2 = 9, then 2 9 = 512.
print(5 > 3 and 2 > 4)
and needs both sides to be True. 2 > 4 is False.
print(not 3 == 3)
3 == 3 is True, and not turns it into False.