Python Operators Examples
Short, runnable programs that show python operators in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Operators lesson.
1Sharing things out with // and %
Floor division tells you how many whole items each person gets; modulo tells you how many are left over. Multiplying back and adding the remainder always gives the original number.
sweets = 47
children = 6
each = sweets // children
left_over = sweets % children
print("Each child gets", each)
print("Left over:", left_over)
print("Check:", each * children + left_over)Expected outputEach child gets 7
Left over: 5
Check: 47
2Even numbers, multiples and last digits with %
A remainder of 0 means one number divides the other exactly. % 10 gives the last digit of a whole number.
number = 42
print(number % 2 == 0) # even?
print(number % 5 == 0) # a multiple of 5?
print(number % 10) # last digitExpected outputTrue
False
2
3Updating a balance with assignment operators
Each shortcut operator updates the variable using its current value. Like /, the /= operator always produces a float.
balance = 100
balance += 25 # deposit
balance -= 40 # pay a bill
print(balance)
balance *= 2 # double it
print(balance)
balance /= 4 # /= always gives a float
print(balance)Expected output85
170
42.5
4Comparing text and chaining comparisons
Strings are compared character by character, and every uppercase letter sorts before every lowercase one — so "Zebra" < "apple". A chained comparison like 13 <= age <= 19 reads just like maths.
print("apple" < "banana")
print("Zebra" < "apple")
print("cat" == "Cat")
age = 15
print(13 <= age <= 19)Expected outputTrue
True
False
True
Practise next
Python Operators exercises → Back to the lesson
Python Strings examplesPython if, elif and else examplesPython Calculator Project examples