1.2.3 Arithmetic, relational and logical operators

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numeric values. All return a numeric result.

OperatorMeaningExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division (real result)7 / 23.5
//Integer division (floor)7 // 23
%Modulus (remainder)7 % 21
**Exponentiation (power)2 ** 8256

Key pair: // and %

Integer division and modulus are complementary. For any division a / b:

  • a // b gives the whole number of times b goes into a
  • a % b gives 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.

OperatorMeaningExampleResult
==Equal to5 == 5True
!=Not equal to5 != 3True
>Greater than7 > 3True
>=Greater than or equal to5 >= 5True
<Less than3 < 7True
<=Less than or equal to3 <= 3True

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.

OperatorMeaningReturns True when...
andBoth conditions must be trueBoth sides are True
orAt least one condition must be trueEither side (or both) is True
notInverts the Boolean valueThe 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 True or False — use == to test equality, never =.
  • and requires both sides true; or requires at least one; not inverts.
  • Logical operators are used to combine relational expressions into compound conditions.