Lesson 5 of 12

Python Operators

An operator is a symbol or keyword that does something with values: + adds, > compares, and combines conditions. You have already used a few. This lesson collects the Python operators you will use daily, explains the ones that surprise beginners (such as //, % and is), and shows how Python decides which part of a long expression to work out first.

Arithmetic operators

OperatorMeaningExampleResult
+Addition7 + 29
-Subtraction7 - 25
*Multiplication7 * 214
/Division (always a float)7 / 23.5
//Floor division (round down)7 // 23
%Remainder (modulo)7 % 21
**Power7 ** 249

// and % are a useful pair. Floor division tells you how many whole groups fit; the remainder tells you what is left over. They answer everyday questions such as “how many full boxes?” and “is this number even?” (a number is even when n % 2 == 0).

laddoos = 50
per_box = 12
print("Full boxes:", laddoos // per_box)
print("Left over:", laddoos % per_box)

minutes = 135
print(f"{minutes} minutes = {minutes // 60} h {minutes % 60} min")

print(2 ** 10)
print(17 % 2 == 0)
print(-7 // 2)
Output
Full boxes: 4
Left over: 2
135 minutes = 2 h 15 min
1024
False
-4

The last line surprises people: -7 // 2 is -4, not -3. Floor division always rounds down towards minus infinity, not towards zero.

The + and * operators also work on strings and lists. "Hi " + "Ram" joins text, and "-" * 20 repeats a dash twenty times, which is a quick way to print a divider line.

Assignment operators

Updating a variable from its own value is so common that Python has shortcuts. total += 50 means exactly total = total + 50. The same pattern works with every arithmetic operator: -=, *=, /=, //=, %= and **=. Python has no ++ or -- operators; write count += 1 instead.

Comparison operators

Comparisons always give a bool: True or False. The operators are == (equal), != (not equal), <, >, <= and >=.

Watch out: = assigns a value; == compares two values. Writing if price = 100: is a syntax error in Python, which at least stops the mistake early.

Python lets you chain comparisons the way you would write them in maths. 18 <= age < 60 means “age is at least 18 and less than 60”, without repeating age. Strings compare letter by letter by their Unicode values, so "apple" < "banana" is True, but every capital letter comes before every small letter.

Logical operators: and, or, not

  • a and b is true only when both sides are true.
  • a or b is true when at least one side is true.
  • not a flips true to false and false to true.

Python stops evaluating as soon as it knows the answer. This is called short-circuiting. In False and anything, the right side is never looked at. Strictly speaking, and and or return one of their operands rather than a plain bool, which gives a handy shortcut: name or "Guest" gives "Guest" when name is an empty string.

age = 34
income = 450000
has_pan = True

print(18 <= age < 60)
print(income > 250000 and has_pan)
print(not has_pan)

customer_name = ""
print("Hello,", customer_name or "Guest")

cart_total = 1200
is_member = False
free_delivery = cart_total >= 999 or is_member
print("Free delivery:", free_delivery)
Output
True
True
False
Hello, Guest
Free delivery: True

Membership and identity

in and not in test whether a value is inside a string, list or other collection: "Ooty" in hill_stations. They read like English and are much clearer than a loop for simple checks.

is checks whether two names point to the very same object in memory, not whether they are equal. Two lists can hold the same items (== is True) and still be different objects (is is False). In everyday code, use is only for comparing with None: if result is None:.

hill_stations = ["Ooty", "Kodaikanal", "Munnar"]
print("Ooty" in hill_stations)
print("Shimla" not in hill_stations)
print("kodai" in "Kodaikanal".lower())

list_a = [1, 2, 3]
list_b = [1, 2, 3]
list_c = list_a
print(list_a == list_b, list_a is list_b, list_a is list_c)

discount = None
print(discount is None)
Output
True
True
True
True False True
True

Python operators and precedence

When an expression has several operators, Python follows a fixed order, much like the BODMAS rule from school maths. From highest to lowest, the main levels are:

  1. Brackets ( )
  2. Power **
  3. Unary minus, as in -x
  4. *, /, //, %
  5. +, -
  6. Comparisons, in, is
  7. not, then and, then or

So 2 + 3 * 4 is 14, and -2 ** 2 is -4, because the power is worked out before the minus sign. When in doubt, add brackets. They cost nothing, and they make your intention clear to the next reader.

Tip: To round money correctly, avoid mixing // with prices: // throws away the paise. Use round(amount, 2) for display, as you saw in Python Data Types.

Python operators really come alive inside decisions, which is the topic of Python Conditions.

Further reading

Key takeaways

  • / always returns a float; // rounds down and % gives the remainder.
  • Use +=, -= and friends to update a variable; there is no ++.
  • Comparisons return True or False and can be chained: 0 < x < 10.
  • and, or and not combine conditions and short-circuit.
  • Use in for membership, == for equality and is mainly for None.

Quick quiz

Check what you learned – pick an answer.

1. What is 23 % 5?

2. What does 2 + 3 * 2 ** 2 evaluate to?

3. Which check is the recommended way to test for None?

Practice exercise

An auto-rickshaw charges ₹30 for the first 2 km and ₹15 for every further km. For a trip of distance_km = 9, calculate and print the fare, and print whether the fare is over ₹100.

Show a hint

Extra kilometres are distance_km - 2. Combine with a comparison that returns True or False.

Show the solution
distance_km = 9

base_fare = 30
extra_km = distance_km - 2
fare = base_fare + extra_km * 15

print(f"Fare for {distance_km} km: ₹{fare}")
print("Over ₹100:", fare > 100)

Progress is saved in this browser only.