1.2.3 Arithmetic, relational and logical operators
Arithmetic Operators
Arithmetic operators perform mathematical calculations on numeric values. All return a numeric result.
| Operator | Meaning | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division (real result) | 7 / 2 | 3.5 |
// | Integer division (floor) | 7 // 2 | 3 |
% | Modulus (remainder) | 7 % 2 | 1 |
** | Exponentiation (power) | 2 ** 8 | 256 |
Key pair: // and %
Integer division and modulus are complementary. For any division a / b:
a // bgives the whole number of times b goes into aa % bgives what is left over
minutes = 137
hours = 137 // 60 # 2 (60 goes into 137 twice)
remaining = 137 % 60 # 17 (137 - 2*60 = 17)
print(hours, "hours and", remaining, "minutes") # 2 hours and 17 minutes
Relational Operators
Relational operators compare two values and return a Boolean result: True or False. They are used in conditions for if statements and loops.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | True |
!= | Not equal to | 5 != 3 | True |
> | Greater than | 7 > 3 | True |
>= | Greater than or equal to | 5 >= 5 | True |
< | Less than | 3 < 7 | True |
<= | Less than or equal to | 3 <= 3 | True |
Note: == tests equality; = assigns a value. Mixing them up is one of the most common errors in programming.
Logical Operators
Logical operators combine Boolean expressions. They are used when a condition depends on more than one test.
| Operator | Meaning | Returns True when... |
|---|---|---|
and | Both conditions must be true | Both sides are True |
or | At least one condition must be true | Either side (or both) is True |
not | Inverts the Boolean value | The operand is False |
age = 17
has_ticket = True
# and: both conditions must be true
if age >= 18 and has_ticket:
print("Admitted")
else:
print("Not admitted") # prints this: age fails
# or: either condition is enough
if age >= 18 or has_ticket:
print("Can proceed") # prints this: ticket is True
# not: inverts
if not has_ticket:
print("Buy a ticket first") # does not print
Key Takeaways
//gives the integer (floor) quotient;%gives the remainder — useful for time conversion, even/odd checks and cycling through values.- Relational operators always return
TrueorFalse— use==to test equality, never=. andrequires both sides true;orrequires at least one;notinverts.- Logical operators are used to combine relational expressions into compound conditions.