๐Ÿ Python for Teens & Beginners ยท Lesson 3 of 7

Math in Python

Google Classroom

Operators, division, remainder and powers.

Operators

+ - *Add, subtract, multiply
/Divide โ†’ 7 / 2 = 3.5
//Floor division (whole part) โ†’ 7 // 2 = 3
%Remainder (modulo) โ†’ 7 % 2 = 1
**Power โ†’ 2 ** 3 = 8

Order of operations

print(2 + 3 * 4)    # 14
print((2 + 3) * 4)  # 20

Python follows PEMDAS: parentheses, exponents, multiplication and division, then addition and subtraction.

Remainder is super useful

n = int(input("A number: "))
print(n % 2)   # 0 = even, 1 = odd

minutes = 135
print(minutes // 60, "hours and", minutes % 60, "minutes")

135 minutes = 2 hours and 15 minutes.

Rounding

price = 19.987
print(round(price, 2))  # 19.99
print(f"${price:.2f}")  # $19.99

Tip

๐Ÿ’ก Updating a variable: score = score + 1 can be written score += 1. Also -=, *= and /=.

โœ๏ธ Practice: your turn

  1. Write a tip calculator: ask for the bill and print a 15%, 18% and 20% tip
  2. Convert seconds into minutes and seconds with // and %
  3. Ask for a number and print whether it is even or odd (just print n % 2 for now)
  4. Calculate 2 to the power of 10

โœ๏ธ Run Python in your browser, no install โ†—

๐Ÿง  Quick quiz

Answer all 4 questions correctly to mark this lesson as done.

1. What is 7 // 2?
2. What is 7 % 2?
3. What is 2 ** 4?
4. What does print(2 + 3 * 4) show?

0 of 4 correct