trylineTryline homeF1 · First steps
About 5 minutes

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)
OUTPUT
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.

TRY IT: DIVIDE 8 BY 2, THEN RUN
OUTPUT
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)
OUTPUT
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.
17 sweets, 5 friends. What does 17 % 5 give?

3. Powers

print(2 ** 3)
OUTPUT
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.

No brackets
print(2 + 3 * 4)
OUTPUT
14
Multiply first: 2 plus 12.
Brackets
print((2 + 3) * 4)
OUTPUT
20
Brackets first: 5 times 4.
What does print(10 - 2 * 3) show?

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)
OUTPUT
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)
OUTPUT
55
hahaha
Text plus a number
print("5" + 5)
TypeError: can only concatenate str (not "int") to str
Mixing text and a number with plus gives a TypeError. Convert first.

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.

BillsBank balances and EMIsSplitting a bill
Ready for your missionKettle & Crumb: "The GST was Rs 200 on a Rs 40 bill!"
Start the mission
Was this page clear?