DMarlon Studio

Lesson 3 · 3 of 20

Numbers and arithmetic · Python

Do maths in Python: whole division with //, remainders with %, powers with ** and rounding with round(), while sharing out some pizzas.

Python · Numbers and arithmetic in DMarlon Studio: the example's code and its output in the terminal

Python adds with +, subtracts with - and multiplies with *. Three pizzas with eight slices each are 3 * 8, that is 24 slices to share among 5 friends.

There are three ways to divide. / gives the exact result, always with decimals (4.8). // is floor division: how many whole slices each friend gets (4). And % gives the remainder: the slices left over (4).

Numbers with a decimal point are float. 12.99 * 3 gives 38.97; round(bill) rounds it to whole euros (39) and round(bill / friends, 2) keeps two decimals (7.79). Remember that Python always uses a point for decimals, never a comma.

** raises to a power: 15 ** 2 is 15 squared. With it the program works out each pizza's area (π · r²), and you can see that the large one is almost twice as big.

As in maths, multiplication comes before addition: 2 + 3 * 4 is 14. Parentheses change the order: (2 + 3) * 4 is 20.

Code · main.py

# Pizza night with friends: let Python do the maths.slices = 3 * 8        # three pizzas, eight slices eachfriends = 5print("Total slices:", slices)print("Each one (exact):", slices / friends)print("Each one (whole):", slices // friends)print("Slices left over:", slices % friends)# Numbers with a decimal point are floats.pizza_price = 12.99bill = pizza_price * 3print("Bill:", bill)print("Rounded to euros:", round(bill))print("Per person:", round(bill / friends, 2))# ** raises to a power: area of a 30 cm and a 40 cm pizza.medium = 3.1416 * 15 ** 2large = 3.1416 * 20 ** 2print("Medium area:", round(medium), "cm2")print("Large area:", round(large), "cm2")# Parentheses decide what is worked out first.print(2 + 3 * 4, (2 + 3) * 4)

Output · python3 main.py

Total slices: 24
Each one (exact): 4.8
Each one (whole): 4
Slices left over: 4
Bill: 38.97
Rounded to euros: 39
Per person: 7.79
Medium area: 707 cm2
Large area: 1257 cm2
14 20

Key points

  • / divides with decimals; // keeps the whole part.
  • % gives the remainder of a division.
  • ** is the power: 2 ** 3 is 8.
  • round(x, 2) rounds to two decimals.
  • Parentheses decide what is worked out first.

Exercise

Change the number of friends to 7 and add a line that says how many extra slices you would need so that everyone gets a fifth one.