Lesson 4 of 6 · Python

Operators and expressions

Operators let Python calculate values and compare information. This lesson covers arithmetic, comparison, logical and assignment operators, including the differences that commonly confuse beginners.

Arithmetic operators

Use +, -, * and / for addition, subtraction, multiplication and division. Python also provides // for floor division, % for the remainder and ** for powers.

For example, 17 // 5 gives 3 and 17 % 5 gives 2. These operators are useful when splitting items into groups or checking whether a number is even.

Comparison and logical operators

Comparison operators such as ==, !=, >, <, >= and <= compare two values. Their result is a Boolean: True or False.

Logical operators combine conditions. and is true only when both sides are true; or is true when at least one side is true; not reverses a Boolean result.

Order of operations

Python evaluates expressions using operator precedence. Parentheses make the intended order explicit and make complicated expressions easier to read. For example, (a + b) * c adds first, then multiplies.

Use the correct operator for the job. A single = assigns a value. Two equals signs, ==, ask whether two values are equal. Mixing them up is a common source of errors.

main.py
a = 17
b = 5

print("Addition:", a + b)
print("Division:", a / b)
print("Whole groups:", a // b)
print("Remainder:", a % b)
print("Power:", b ** 2)
compare.py
age = 19
has_id = True

can_enter = age >= 18 and has_id
print("Allowed:", can_enter)
print("Not allowed:", not can_enter)

Try it yourself

The code examples above are for reference. Copy the relevant example into the editor, press Run, then change it and run it again.

Code Campus
Your turn

Take a number from the user and print whether it is even. Use the remainder operator instead of checking the last digit.

Show a hint
number = int(input("Enter a number: "))
print(number % 2 == 0)

#CodeCampus

Code Campus