๐Ÿ Lesson 4: Numbers & Math

Turn Python into a super-calculator

โ† Back to Python Basics

โž• The math operators

Python knows all the basic math symbols:

print(5 + 3) # 8 addition print(5 - 3) # 2 subtraction print(5 * 3) # 15 multiplication (use * not ร—) print(6 / 3) # 2.0 division (always gives a float)

๐Ÿ“Œ Division always makes a float

6 / 3 gives 2.0, not 2. The decimal point tells you it's a float.

โœจ Three special operators

Power **

print(2 ** 3) # 8 (2 to the power of 3) print(5 ** 2) # 25 (5 squared)

Floor division // โ€” divide and drop the decimal

print(7 // 2) # 3 (not 3.5)

Modulo % โ€” the remainder

print(7 % 2) # 1 (7 รท 2 = 3 remainder 1) print(10 % 5) # 0 (divides evenly)

The % operator is super useful for checking if a number is even (n % 2 == 0) or odd.

๐Ÿ”ข Order of operations

Python follows the same rules as math class (PEMDAS). Use parentheses to control the order:

print(2 + 3 * 4) # 14 (multiply first) print((2 + 3) * 4) # 20 (parentheses first)

๐Ÿ”„ Converting between text and numbers

You can't add text and numbers directly

"5" + 3 causes an error! "5" is a string, 3 is a number.

Convert with int(), float(), and str():

print(int("5") + 3) # 8 text โ†’ number print(str(5) + " cats") # 5 cats number โ†’ text print(float("2.5")) # 2.5

๐Ÿงฎ Math shortcuts

Update a variable quickly with +=, -=, *=:

score = 10 score += 5 # same as score = score + 5 print(score) # 15 score *= 2 print(score) # 30

โœ… What you learned

  • Operators: + - * /, plus ** (power), // (floor), % (remainder).
  • Parentheses control the order of operations.
  • Convert with int(), float(), str().
  • Shortcuts: +=, -=, *=.