Bài học theo mô-đun (2/4)
Toán tử
Operators are the symbols that combine values to produce new ones. Python shares most operators with other languages, but introduces some very useful ones of its own.
Arithmetic operators
3 + 2 # 5 somma
3 - 2 # 1 differenza
3 * 2 # 6 prodotto
7 / 2 # 3.5 divisione (restituisce SEMPRE float)
7 // 2 # 3 divisione intera (tronca verso il basso)
7 % 2 # 1 resto (modulo)
2 ** 10 # 1024 potenzaComparison operators
They return a bool (True or False):
3 == 3 # True uguaglianza
3 != 4 # True diversità
3 < 4 # True minore
3 <= 3 # True minore o uguale
"a" < "b" # True confronto lessicograficoUnlike JavaScript, in Python there is only one equality
operator (==): no need to choose between == and ===.
Logical operators
They are written with English words, not symbols:
True and False # False
True or False # True
not True # FalseThey also have a very useful short-circuit behavior: a and b
returns a if it's "falsy", otherwise b.
What counts as "falsy"
In Python, these are considered false: False, None, 0, 0.0, the empty string
"", the empty list [], the empty dict {}. Everything else is considered true.
Priority in brief
To memorize: ** → * / // % → + - → comparisons → not → and →
or. When in doubt, use parentheses: they cost nothing and make the
code more readable.
Floor division and rounding
The floor division operator // always truncates the result down to the next integer. This means that for positive numbers 7 // 2 yields 3, but for negative numbers -7 // 2 yields -4.
The modulo operator % calculates the remainder of integer division and is widely used to determine whether a number is a multiple of another (e.g. n % 2 == 0 checks if n is even).
Try it yourself
Calculate the square of 9 plus the cube of 2 and assign it to `result`. Then evaluate `result`.
Hiển thị gợi ý
9 ** 2 is 81, 2 ** 3 is 8: the sum is 89.
Giải pháp khả dụng sau 3 lần thử
Review exercise
Create a variable `is_even` that says (True/False) whether the number 17 is even, using the modulo operator.
Hiển thị gợi ý
A number is even when its remainder modulo 2 is 0.
Giải pháp khả dụng sau 3 lần thử
Additional challenge
Use floor division to calculate how many times 3 goes into 10, calculate the remainder using modulo, and check if this remainder is not equal to 0. Store the boolean verdict in `is_not_multiple`. Finally, evaluate the variable.
Hiển thị gợi ý
Use 10 // 3 for floor division and 10 % 3 for modulo.
Giải pháp khả dụng sau 3 lần thử