Operators let Python calculate values and compare information. This lesson covers arithmetic, comparison, logical and assignment operators, including the differences that commonly confuse beginners.
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 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.
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.
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)
age = 19
has_id = True
can_enter = age >= 18 and has_id
print("Allowed:", can_enter)
print("Not allowed:", not can_enter)
Take a number from the user and print whether it is even. Use the remainder operator instead of checking the last digit.
number = int(input("Enter a number: "))
print(number % 2 == 0)