Questions or a demo for your school?Student? Sit a test
BrainBit Infotech TeachingStart free

Python notes · Topic 3 of 22 · 4 min read

Python operators and expressions

Python operators notes with examples: arithmetic, floor division and modulus, precedence, assignment, comparison and logical operators, round() and abs().

Arithmetic operators

OperatorNameExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide7 / 23.5
//floor division7 // 23
%modulus (remainder)7 % 21
**power7 ** 249

/ always gives a float, even when the answer is whole: 8 / 2 is 4.0.

Floor division and remainder

Think of sharing 17 chocolates among 5 children:

chocolates = 17
children = 5
each = chocolates // children     # 3 chocolates each
left = chocolates % children      # 2 left over

% has many uses:

  • n % 2 == 0 checks if a number is even.
  • n % 10 gives the last digit of a number.
  • seconds % 60 gives the seconds left after taking out whole minutes.
total = 3725
hours = total // 3600            # 1
minutes = (total % 3600) // 60   # 2
seconds = total % 60             # 5

Precedence: Python follows BODMAS

Python works out operators in this order, highest first:

  1. () brackets
  2. ** power
  3. *, /, //, %
  4. +, -

Operators on the same level are worked out left to right, except **, which goes right to left.

print(2 + 3 * 4)       # 14, not 20
print((2 + 3) * 4)     # 20
print(2 ** 3 ** 2)     # 512, because 3 ** 2 is done first

When in doubt, add brackets. They make the order clear to anyone reading your code.

Assignment operators

A shortcut for "update a variable using its own value":

Short formMeans
x += 5x = x + 5
x -= 5x = x - 5
x *= 2x = x * 2
x /= 2x = x / 2
x //= 2x = x // 2
x %= 3x = x % 3

Python has no x++ or x--. Write x += 1.

Comparison operators

Each comparison gives True or False.

OperatorMeaning5 ? 3
==equal toFalse
!=not equal toTrue
>greater thanTrue
<less thanFalse
>=greater than or equalTrue
<=less than or equalFalse

= stores a value; == compares two values. Mixing them up is a very common mistake.

Python allows chained comparisons: 0 <= marks <= 100 checks both limits at once.

Logical operators: and, or, not

OperatorTrue whenExample
andboth sides are trueage >= 18 and has_id
orat least one side is trueday == "Sat" or day == "Sun"
notflips the valuenot is_absent
marks = 72
attendance = 80
can_sit_exam = marks >= 33 and attendance >= 75
print(can_sit_exam)      # True

Built-in maths functions

print(round(3.14159, 2))   # 3.14
print(abs(-7))             # 7
print(max(4, 9, 2))        # 9
print(min(4, 9, 2))        # 2
print(pow(2, 10))          # 1024, same as 2 ** 10

Example: GST bill

price = float(input("Price of the phone: "))
gst = price * 18 / 100
total = price + gst
print(f"GST: Rs {gst:.2f}")
print(f"Total: Rs {total:.2f}")

Common mistakes

  • Expecting / to give a whole number. Use // for that.
  • Writing if x = 5 instead of if x == 5.
  • Forgetting brackets: a + b / 2 is not the average of a and b; (a + b) / 2 is.
  • Writing 0 < x and < 10. Each side of and must be a full comparison: 0 < x and x < 10.

Key points

  • // gives the whole-number part of a division and % gives the remainder.
  • Precedence follows BODMAS; brackets override it.
  • Comparisons give True or False; combine them with and, or, not.
  • x += 1 is the Python way to add one.

Practice questions

1. What are the values of 17 // 4, 17 % 4 and 17 / 4?

4, 1 and 4.25.

2. What does print(10 - 4 / 2 * 3) show?

4.0. First 4 / 2 is 2.0, then 2.0 * 3 is 6.0, then 10 - 6.0 is 4.0.

3. Write an expression that is True when a year is a leap year.
(year % 4 == 0 and year % 100 != 0) or year % 400 == 0
4. A number is stored in n. How do you get its last digit?

n % 10. For example, 347 % 10 is 7.

5. What is the value of not (5 > 3 and 2 > 4)?

True. 5 > 3 is True and 2 > 4 is False, so the and is False, and not False is True.