Numbers and Maths

Programming Languages · Python Basics · 10 min

Use Python as a calculator: the main operators, brackets, decimals and rounding.

Python as a calculator

Python knows the usual maths symbols:

print(8 + 2)   # 10  add
print(8 - 2)   # 6   subtract
print(8 * 2)   # 16  multiply
print(8 / 2)   # 4.0 divide

Let Python do the work: write the sum, not the answer.

  • Print the result of 15 + 27.

  • Print the result of 9 * 6.

Whole division and remainders

/ always gives a decimal: 7 / 2 is 3.5. Two more division tools are handy:

  • // divides and drops the decimal part: 7 // 2 is 3
  • % gives the remainder, what's left over: 7 % 2 is 1

Think of 7 sweets shared by 2 kids: 3 each, 1 left over.

  • Print 17 // 5.

  • Print 17 % 5.

Powers

Two stars ** mean "to the power of". 3 ** 2 is 3 times 3, which is 9. 2 ** 3 is 2 times 2 times 2, which is 8.

print(5 ** 2)  # 25
  • Print 2 ** 10.

  • Print the area of the square: side to the power of 2.

Order of operations

Python follows the maths rules you learned at school: ** first, then * / // %, then + -.

print(2 + 3 * 4)    # 14, the * happens first
print((2 + 3) * 4)  # 20, brackets go first

When in doubt, add brackets. They make your intent clear.

  • Add brackets to the line so it prints 20 instead of 14.

Whole numbers and decimals

Python has two kinds of numbers:

  • an int is a whole number: 7
  • a float has a decimal point: 7.5

round(x, 2) rounds to 2 decimal places, and int(x) chops off the decimal part:

print(round(3.14159, 2))  # 3.14
print(int(3.9))           # 3
  • Print price rounded to 2 decimal places.

  • Print price as a whole number with int().

Put it together: split the bill

Four friends ordered pizza. Work out what each person pays, then share out the slices fairly. Use the variables so it would still work if the numbers changed.

  • Create share: the bill divided by people.

  • Print share rounded to 2 decimal places.

  • Print the slices each person gets (slices // people), then the slices left over (slices % people).

More in Python Basics

Previous: Variables · Next: Strings