Python for Beginners: Learn to Code from Zero · Lesson 3 of 10

Lesson 3: Numbers and Operators

Do maths in Python, compare values and combine conditions with and, or and not.

Lesson 3: Numbers and Operators

Arithmetic

OperatorMeaningExampleResult
+add7 + 29
-subtract7 - 25
*multiply7 * 214
/divide (always a decimal)7 / 23.5
//divide, drop the remainder7 // 23
%remainder7 % 21
**power7 ** 249
print(7 + 2)
print(7 / 2)
print(7 // 2)
print(7 % 2)
print(7 ** 2)

Output:

9
3.5
3
1
49

A real example: you buy 3 notebooks at Rs 45 each and pay with a Rs 200 note.

price = 45
count = 3
total = price * count
change = 200 - total
print("Total:", total)
print("Change:", change)

Output:

Total: 135
Change: 65

Order of operations

Python follows the usual maths order: brackets, then powers, then multiply and divide, then add and subtract. Use brackets to be clear.

print(2 + 3 * 4)
print((2 + 3) * 4)

Output:

14
20

Comparing values

Comparisons give True or False: == (equal), != (not equal), <, >, <=, >=. Notice that == compares, while a single = stores.

marks = 62
print(marks >= 40)
print(marks == 100)
print(marks != 62)

Output:

True
False
False

Combining conditions

and needs both sides to be true, or needs at least one, and not flips the answer.

age = 17
has_card = True
print(age >= 16 and has_card)
print(age < 10 or has_card)
print(not has_card)

Output:

True
True
False

Try it yourself

  1. Work out the area of a rectangle 12 cm by 7 cm with variables.
  2. Find the remainder when 2026 is divided by 7.
  3. Check whether a number is even using %.

Next lesson: making your program decide with if.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 3: Numbers and Operators | MeroSir