SyntaxPilot
Courses/Python/Lesson 4

Python · Lesson 4 of 40 · 15 min

Operators: arithmetic, comparison, logical, assignment

queued

These are the notes for Python episode 4. You will learn how Python calculates and decides: floor division // and the remainder %, why 2 ^ 10 prints 8, powers with **, operator precedence (who goes first), the comparison operators == != < > <= >=, chained comparisons like 18 <= age <= 60, the logical operators and, or, not with short-circuit evaluation, and the assignment shortcuts +=, -=, *=. Every example below runs as-is in the SyntaxPilot compiler (type the input in the input box before you press Run), with its real output from Python 3.13.

Three words first: operator, operand, expression

In total = price * cups, the * is an operator: a symbol that does an action (multiply). price and cups are the operands: the values the operator works on. And price * cups is an expression: a piece of code that Python works out into a single value.

The problem: four friends, one bill

Four friends finish chai and samosas at Raju's stall. The bill is ₹450. Normal division says 450 / 4 = 112.5, but nobody carries 50 paise coins any more. Each friend pays in whole rupees, so we need two answers: how many whole rupees each, and how many rupees are left over.

Floor division // and modulo %

print(450 / 4)
print(450 // 4)
print(450 % 4)
112.5
112
2
  • / is normal division. It always gives a float (a decimal number), even when it divides exactly: 10 / 2 is 5.0.
  • // is floor division: it divides and keeps only the whole part. Each friend pays ₹112.
  • % is the modulo operator: it gives the remainder, what's left over after dividing. ₹2 is left over (4 × 112 = 448, and 450 − 448 = 2).

Real-life picture: packing samosas into boxes

Raju packs 23 samosas into boxes of 6. How many full boxes? 23 // 6. How many loose samosas are left on the tray? 23 % 6.

samosas = 23
print("Boxes:", samosas // 6)
print("Left over:", samosas % 6)
Boxes: 3
Left over: 5

Floor division counts the full boxes; modulo counts the leftovers.

Two famous uses of %

print(17 % 2, 18 % 2)
print(2026 % 10)
1 0
6
  • Even or odd: a number is even when n % 2 is 0. 17 leaves 1 (odd), 18 leaves 0 (even).
  • Last digit: n % 10 gives the last digit of a positive number. 2026 % 10 is 6. Both tricks come up again and again in coding interviews.

Edge cases: negative numbers and floats

"Floor" means round down (towards minus infinity), not "cut off the decimals". For positive numbers it's the same thing, but not for negatives. print(-7 // 2, -7 % 2, 7 // -2, 7.5 // 2) prints -4 1 -4 3.0:

  • -7 / 2 is -3.5, and rounding down gives -4, not -3.
  • -7 % 2 is 1, because Python keeps (a // b) * b + a % b == a: -4 * 2 + 1 = -7. In Python the remainder always has the sign of the number you divide by.
  • If either operand is a float, // gives a float: 7.5 // 2 is 3.0.
  • Dividing by zero crashes the program with // and % too: 1 // 0 gives ZeroDivisionError: integer division or modulo by zero (more on this error below).

The 2 ^ 10 trap and ** for power

If ₹1 doubles 10 times, it becomes ₹1024: that's 2 to the power 10 (2 multiplied by itself 10 times). The exponent is the small number that says how many times: 10. On a calculator or in Excel you type 2^10. In Python, print(2 ^ 10) prints 8.

No error, just a wrong answer. In Python ^ is a different operator called XOR ("exclusive or"). It works on the binary bits of numbers (1010 XOR 0010 = 1000, which is 8). You won't need it for a long time. The dangerous part: Python doesn't warn you. Power in Python is two stars, **:

print(2 ^ 10)
print(2 ** 10)
print(1.05 ** 10)
8
1024
1.628894626777442

1.05 ** 10 is money growing at 5% a year for 10 years: ₹1 becomes about ₹1.63. That's compound interest (interest earned on interest) in one line. Edge cases: 2 ** -1 is 0.5, 2 ** 0.5 is the square root 1.4142135623730951, and ** works right to left: 2 ** 3 ** 2 is 2 ** 9 = 512.

Precedence: who goes first

Priya scored 80 and 90 in two tests. Her average is 85. We type it the way we say it, print(80 + 90 / 2), and get 125.0: an average higher than the maximum marks! Python did the division first: 90 / 2 = 45.0, then 80 + 45.0 = 125.0. Brackets fix it:

print(80 + 90 / 2)
print((80 + 90) / 2)
125.0
85.0

Operator precedence is the order in which Python applies operators, like the BODMAS rule from school maths:

Rank Operators Meaning
1 ( ) brackets
2 ** power
3 * / // % the multiply and divide family
4 + - add and subtract
5 == != < > <= >= comparisons
6 not, then and, then or logical operators
  • Same rank? Python goes left to right: 10 - 4 - 3 is 3. (Exception: ** goes right to left.)
  • ** beats the minus sign in front of a number: -2 ** 2 is -4, but (-2) ** 2 is 4.
  • Not sure? Add brackets. They cost nothing and make your intention clear to Python and to the next reader.

Comparison operators: asking questions

An office orders 12 cups, and Raju's offer is "more than 10 cups gets 10% off". The program must ask a yes/no question: is 12 more than 10? Most people's first try is the equals sign:

cups = 12
print(cups = 12)
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(cups = 12)
    ~~~~~^^^^^^^^^^^
TypeError: print() got an unexpected keyword argument 'cups'

A single = never asks a question: it means store this value. Inside print(), Python thought you were passing a setting named cups. To ask, use ==:

cups = 12
print(cups > 10)
print(cups == 12, cups != 12)
print(cups <= 11)
True
True False
False

A comparison operator compares two values and answers with a boolean: True or False (the bool type from episode 2).

Operator Meaning Example Result
== equal to 12 == 12 True
!= not equal to 12 != 12 False
> greater than 12 > 10 True
< less than 12 < 10 False
>= greater than or equal to 12 >= 12 True
<= less than or equal to 12 <= 11 False

The = always comes second: >= and <=. Writing x => 3 gives SyntaxError: invalid syntax.

Surprises with text

print("10" == 10)
print("apple" < "banana")
print("Zebra" < "apple")
False
True
True
  • "10" == 10 is False: text and a number are never equal, even if they look the same. Remember input() gives text, so convert with int() first.
  • Strings compare like a dictionary, letter by letter, so "apple" < "banana".
  • But "Zebra" < "apple" is also True! Python compares the letters' character codes, and every capital letter comes before every small letter (ord("Z") is 90, ord("a") is 97). To compare ignoring case, use "Zebra".lower() < "apple" (which is False).

Chained comparisons

A bus pass is for adults aged 18 to 60. In maths you write 18 ≤ age ≤ 60, and Python lets you write exactly that: with age = 25, print(18 <= age <= 60) prints True. This is a chained comparison. Python checks both parts: 18 <= age and age <= 60. Most languages can't do this; Python can.

Logical operators: and, or, not

Real offers have more than one condition: a student discount only if the customer is a student and orders more than 5 cups. Let's start simpler: is someone a teenager (13 to 19)? Written the way we say it in English:

age = 16
print(age >= 13 and <= 19)
  File "main.py", line 2
    print(age >= 13 and <= 19)
                        ^^
SyntaxError: invalid syntax

In English we can skip "age" the second time. Python can't: each side of and must be a complete question. With age = 16, both print(age >= 13 and age <= 19) and the chained print(13 <= age <= 19) print True.

Logical operators combine True/False answers:

Real life In Python Rule
Airport gate: ticket and ID a and b True only if both are True
Paying at the stall: cash or UPI a or b True if at least one is True (False only when both are False)
"No entry" sign flips "allowed" not a flips True ↔ False
student = True
cups = 6
print(student and cups > 5)
print(student or cups > 5)
print(not student)
True
True
False

The or trap

Is cups 1 or 2?

cups = 5
print(cups == 1 or 2)
print(cups == 1 or cups == 2)
2
False

The first line printed 2, not True or False! Python read it as (cups == 1) or (2). cups == 1 is False, so or gives back the other side: the number 2. In an if statement, any non-zero number counts as true ("truthy", from episode 3), so this check would always pass. The fix: repeat the comparison on each side, cups == 1 or cups == 2. (In fact and/or return one of their operands, not always a bool: 0 or "hi" is "hi", 5 and 7 is 7. not always returns True or False.)

Short-circuit: and saves a crash

What if no friends turned up?

friends = 0
print(450 / friends)
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(450 / friends)
          ~~~~^~~~~~~~~
ZeroDivisionError: division by zero

You can't split a bill among nobody, and dividing by zero crashes the program with a ZeroDivisionError. Put a guard in front:

friends = 0
print(friends != 0 and 450 / friends > 100)
False

No crash! and stops as soon as it finds a False, because then the whole answer must be False, so the division never runs. This is short-circuit evaluation: Python skips the right side when the left side already decides the answer. or does the same with the first True. Put the safety check first.

Assignment operators: += and friends

Raju's cash box starts every morning at ₹0. A customer pays ₹12: take the old total, add 12, put it back. The long way, total = 0, then total = total + 12 twice, then print(total), prints 24. It works, but we typed total twice on every update line. The short way is an augmented assignment (an operator and = together):

total = 0
total += 12
total += 12
total -= 5
total *= 2
print(total)
38

Step by step: 12, 24, 19 (bought milk for ₹5), then 38 (doubled). total += 12 means exactly total = total + 12.

Every arithmetic operator has one. Starting each time from x = 10: x += 2 → 12, x -= 2 → 8, x *= 2 → 20, x /= 2 → 5.0 (a float, like /), x //= 3 → 3, x %= 3 → 1, x **= 2 → 100.

Coming from C or Java? You'll try total++:

total = 0
total++
  File "main.py", line 2
    total++
           ^
SyntaxError: invalid syntax

Python has no ++ or --. Write total += 1. Watch out: ++total is not an error, it's just two plus signs ("plus plus total") and changes nothing, so total stays the same.

Common mistakes (and the real error messages)

Mistake Error Why Fix
print(2 ^ 10) no error: prints 8 ^ is XOR, not power 2 ** 10
print(80 + 90 / 2) no error: prints 125.0 / goes before + (80 + 90) / 2
print(cups = 12) TypeError: print() got an unexpected keyword argument 'cups' = stores, == compares print(cups == 12)
x => 3 SyntaxError: invalid syntax the = comes second x >= 3
"10" == 10 expecting True no error: False text is never equal to a number int("10") == 10
age >= 13 and <= 19 SyntaxError: invalid syntax each side needs a full comparison 13 <= age <= 19
cups == 1 or 2 no error: gives 2 (always truthy) or 2 is not a comparison cups == 1 or cups == 2
450 / friends with friends = 0 ZeroDivisionError: division by zero can't divide by zero friends != 0 and ...
-7 // 2 expecting -3 no error: -4 floor rounds down int(-7 / 2) to cut towards zero
total++ SyntaxError: invalid syntax Python has no ++ total += 1

Mini project: leap year checker

The real calendar rule: a year divisible by 4 is a leap year (2024), but not if it's divisible by 100 (1900), unless it's also divisible by 400 (2000). "Divisible" means the remainder is zero: a job for %.

# Mini project: leap year checker
year = int(input("Year: "))

by4 = year % 4 == 0
not100 = year % 100 != 0
by400 = year % 400 == 0

leap = by4 and not100 or by400
print(year, "is a leap year:", leap)
Input Output
2024 Year: 2024 is a leap year: True
1900 Year: 1900 is a leap year: False
2000 Year: 2000 is a leap year: True

(In the SyntaxPilot compiler the typed input isn't echoed, so the prompt and the output appear on one line.)

It uses every kind of operator from today: arithmetic (%), comparison (==, !=), logical (and, or) and assignment (=). and is done before or, so no brackets are needed, though (by4 and not100) or by400 reads even clearer. Try your own birth year!

Practice

  1. Convert 135 minutes into hours and minutes.
Solution
minutes = int(input("Minutes: "))
hours = minutes // 60
left = minutes % 60
print(hours, "hours and", left, "minutes")

Input 135 → Minutes: 2 hours and 15 minutes

  1. Read a number and print True if it's even, False if it's odd.
Solution
n = int(input("Number: "))
print(n % 2 == 0)

Input 14 → Number: True; input -7 → Number: False

  1. Read principal, rate (%) and years, and print the simple interest (P * R * T / 100) and the compound interest (P * (1 + R / 100) ** T - P).
Solution
p = float(input("Principal: "))
r = float(input("Rate %: "))
t = int(input("Years: "))
simple = p * r * t / 100
amount = p * (1 + r / 100) ** t
print("Simple interest:", simple)
print("Compound interest:", round(amount - p, 2))

Input 1000, 5, 3 → Principal: Rate %: Years: Simple interest: 150.0, then Compound interest: 157.63

  1. Read a number and print whether it's between 1 and 100 (inclusive), using a chained comparison.
Solution
n = int(input("Number: "))
print(1 <= n <= 100)

Input 42 → Number: True; input 150 → Number: False

Quick quiz

What does this print?

print(7 // 2 * 2 + 7 % 2)

A) 7 B) 8 C) 7.0 D) 6

Answer

A) 7. //, * and % have the same rank and go left to right: 7 // 2 is 3, times 2 is 6. 7 % 2 is 1. Then 6 + 1 = 7. Floor division and % on ints give ints, so there's no .0.

Interview questions

  1. What is the difference between / and //? / is true division and always returns a float (10 / 2 is 5.0). // is floor division: it rounds down to a whole number (7 // 2 is 3, -7 // 2 is -4).
  2. What does ^ do in Python? Bitwise XOR, not power. 2 ^ 10 is 8. Power is ** (or pow()).
  3. What is short-circuit evaluation? and stops at the first falsy operand and or stops at the first truthy one, so the rest is never evaluated. It's used for guards like n != 0 and total / n > 5.
  4. What does x == 1 or 2 evaluate to, and why is it a bug? It's (x == 1) or 2, so it gives True or 2, which is always truthy. Write x == 1 or x == 2 (or x in (1, 2)).
  5. Does Python have ++? No. x++ is a SyntaxError; use x += 1. ++x is legal but does nothing (two unary plus signs).
  6. How does a < b < c work? It's a chained comparison, meaning a < b and b < c, with b evaluated only once.

Glossary

Term Meaning Example
Operator A symbol that does an action on values *, +, ==, and
Operand A value an operator works on price and cups in price * cups
Expression Code that Python works out into a single value price * cups, age >= 18
Arithmetic operator Does maths + - * / // % **
Division / Normal division; always gives a float 450 / 4 → 112.5
Floor division // Divides and rounds down to a whole number 450 // 4 → 112, -7 // 2 → -4
Modulo % Gives the remainder after division 450 % 4 → 2
Remainder What's left over after dividing into equal whole parts 23 samosas in boxes of 6 → 5 left
Even / odd Remainder by 2 is 0 / 1 18 % 2 → 0
Power / exponent ** Multiply a number by itself; the exponent says how many times 2 ** 10 → 1024
Compound interest Interest earned on earlier interest too 1.05 ** 10 → 1.628...
XOR ^ "Exclusive or" on binary bits; not power 2 ^ 10 → 8
Precedence The order in which operators are applied (like BODMAS) 80 + 90 / 2 → 125.0
Comparison operator Compares two values and gives True/False == != < > <= >=
Boolean (bool) The type with only two values, True and False cups > 10 → True
Character code The number behind each letter; capitals are smaller ord("Z") → 90, ord("a") → 97
Chained comparison Several comparisons in a row, all must hold 18 <= age <= 60
Logical operator Combines True/False answers: and (both), or (at least one), not (flips) True and False → False, not True → False
Truthy / falsy Values that act as True / False in conditions 2 is truthy, 0 is falsy
Short-circuit evaluation Skipping the right side when the left side already decides friends != 0 and 450 / friends > 100
ZeroDivisionError The error when you divide by zero 450 / 0
TypeError An operation or call given something it can't take print(cups = 12)
SyntaxError Code that isn't valid Python grammar total++
Assignment operator = Stores a value in a variable total = 0
Augmented assignment An operator and = together: update in place total += 12
Leap year Divisible by 4, except by 100, unless by 400 2024, 2000 (not 1900)

Summary

  • / gives a float; // gives the whole part (rounding down, so -7 // 2 is -4); % gives the remainder.
  • n % 2 == 0 checks even; n % 10 gives the last digit.
  • ** is power. ^ is XOR, and 2 ^ 10 silently prints 8.
  • Precedence: brackets, **, * / // %, + -, comparisons, not, and, or. When in doubt, add brackets.
  • = stores, == asks. The six comparisons give True or False; "10" == 10 is False and capitals sort before small letters.
  • Chain comparisons: 18 <= age <= 60.
  • and needs both, or needs one, not flips. Each side must be a full comparison: cups == 1 or cups == 2.
  • and/or short-circuit, so put the safety check first.
  • +=, -=, *= and friends update a variable; Python has no ++.

Next episode: Strings: indexing, slicing, methods, f-strings.