Python Arena
Step 2 of 5

Order of operations

A calculation is made of operands, the values, and operators, such as + and *. When a calculation has several operators, Python works them out in the order you know from mathematics:

  1. whatever is in parentheses
  2. powers, **
  3. multiplication and division: *, /, // and %
  4. addition and subtraction: + and -

Operators on the same level are worked out from left to right. Powers are the exception: 2 ** 3 ** 2 is worked out from the right, as 2 ** 9.

print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 * 3 ** 2)
print(20 - 8 - 2)
print(20 - (8 - 2))
Output
14
20
18
10
14

In 2 * 3 ** 2, the power comes first: 3 ** 2 is 9, and 2 * 9 is 18. In 20 - 8 - 2, Python goes from left to right: 20 - 8 is 12, and 12 - 2 is 10. The parentheses in the last line make Python do 8 - 2 first.

A classic mistake

The mean of two numbers is their sum divided by two. Forget the parentheses, and only the second number is divided:

first = 8
second = 6
wrong = first + second / 2
right = (first + second) / 2
print(wrong)
print(right)
Output
11.0
7.0

Python gave no error: first + second / 2 is a perfectly good calculation, just not the one that was meant. Its result is 8 + 3.0, which is 11.0. Python always does what the code says, so check that the order of the calculation is what you want.

Parentheses in a longer formula

Here the price of a product drops by 25 percent, and then shipping is added:

price = 80
discount = 25
shipping = 5
total = price * (100 - discount) / 100 + shipping
print(total)
Output
65.0

The parentheses make Python work out the share of the price you pay, 75 percent, first. Then * and / go from left to right: 80 * 75 is 6000, and 6000 / 100 is 60.0. The addition comes last. When you aren't sure of the order, add parentheses: they never hurt, and they make the formula easier to read.

Your task

Challenge 1 of 3

Fill in the blanks with parentheses so the program prints 30, not 22.

30

Challenge 2

What does this program print? Type each line it prints.

Challenge 3

The program should print the mean of three days' practice hours, but it prints a much bigger number. Fix the calculation, so the program prints:

Mean: 7.0