Skip to main content
eLearner.app
Module 1 · Lesson 2 of 42/36 in the course~10 min
Module lessons (2/4)

Operators

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

Python
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   potenza

Comparison operators

They return a bool (True or False):

Python
3 == 3        # True   uguaglianza
3 != 4        # True   diversità
3 < 4         # True   minore
3 <= 3        # True   minore o uguale
"a" < "b"     # True   confronto lessicografico

Unlike 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:

Python
True and False    # False
True or False     # True
not True          # False

They 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 → notandor. 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

Exercise#python.m1.l2.e1
Attempts: 0Loading…

Calculate the square of 9 plus the cube of 2 and assign it to `result`. Then evaluate `result`.

Loading editor…
Show hint

9 ** 2 is 81, 2 ** 3 is 8: the sum is 89.

Solution available after 3 attempts

Review exercise

Exercise#python.m1.l2.e2
Attempts: 0Loading…

Create a variable `is_even` that says (True/False) whether the number 17 is even, using the modulo operator.

Loading editor…
Show hint

A number is even when its remainder modulo 2 is 0.

Solution available after 3 attempts

Additional challenge

Exercise#python.m1.l2.e3
Attempts: 0Loading…

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.

Loading editor…
Show hint

Use 10 // 3 for floor division and 10 % 3 for modulo.

Solution available after 3 attempts