๐ Python for Teens & Beginners ยท Lesson 3 of 7
Math in Python
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) # 20Python 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.99Tip
๐ก Updating a variable: score = score + 1 can be written score += 1. Also -=, *= and /=.
โ๏ธ Practice: your turn
- Write a tip calculator: ask for the bill and print a 15%, 18% and 20% tip
- Convert seconds into minutes and seconds with // and %
- Ask for a number and print whether it is even or odd (just print n % 2 for now)
- Calculate 2 to the power of 10
๐ง Quick quiz
Answer all 4 questions correctly to mark this lesson as done.
0 of 4 correct
All lessons in Python for Teens & Beginners
- ๐ 1. Your first programprint, quotation marks, and error messages
- ๐ฆ 2. Variables and inputStore information and ask the user
- ๐งฎ 3. Math in PythonOperators, division, remainder and powers
- ๐ 4. Conditions: if and elseThe program decides by itself
- ๐ 5. Loops: for and whileRepeat code without copying it
- ๐ 6. ListsMany values in one variable
- ๐ฒ 7. Project: a guessing gameThe computer picks a number, and you guess