Maths in Python
Python can do maths like a calculator. You'll add, divide, share things out, and do maths with what the user types.
1. The basic four
print(10 + 4) print(10 - 4) print(10 * 4) print(10 / 4)
14 6 40 2.5
*Star multiplies: 10 * 4 is 40./Slash divides, and always gives a decimal: 10 / 4 is 2.5.Notice: / always gives a decimal number, even for 8 / 2. You get 4.0, not 4.
Press Run
2. Whole part and leftover
Python has two more division signs. Double slash divides and keeps only the whole part. Percent gives what's left over after dividing. Say 10 sweets, shared between 3 friends.
print(10 // 3) print(10 % 3)
3 1
//Double slash divides and keeps only the whole part: 10 // 3 is 3.%Percent gives the leftover after dividing: 10 % 3 is 1. In Python, percent means leftover, not percentage.3. Powers
print(2 ** 3)
8
Double star means 'to the power of'. 2 to the power 3: 2 times 2 times 2. That's 8.
4. Which goes first
Python uses the order you learned in school. Multiply before add. Round brackets go first. When in doubt, add brackets.
print(2 + 3 * 4)
14
print((2 + 3) * 4)
20
5. Maths with variables and input
This is where it gets useful. The user types 49.5 and 2. Python multiplies the two values. Remember to convert input first, or it's text.
price = float(input("Price: "))
qty = int(input("How many: "))
print(price * qty)Price: 49.5 How many: 2 99.0
6. One thing to watch
Plus and star also work on text, but differently. Plus joins text: 55, not 10. Star repeats it: hahaha.
print("5" + "5")
print("ha" * 3)55 hahaha
print("5" + 5)7. Where it's used
Every bill, every bank balance, every EMI. Splitting a bill uses double slash and percent. Interest uses star and double star.