Average of Three Numbers
The problem: ask the user for the marks of three subjects and display the average. The maths is from primary school. The trap is one pair of brackets — and if you get it wrong, Python will not tell you.
1Plan it first
- three marks:
a,b,c
total = a + b + cavg = total / 3
- the average, with a message
Notice the process is written as two steps. You could do it in one, but splitting it is easier to read and much easier to check — and it makes the brackets look after themselves.
2The program
# program to find the average of three numbers
a = float(input('Enter the first number: '))
b = float(input('Enter the second number: '))
c = float(input('Enter the third number: '))
total = a + b + c
avg = total / 3
print('Total =', total)
print('Average =', avg)Enter the first number: 40 Enter the second number: 50 Enter the third number: 60 Total = 150.0 Average = 50.0
Why float() and not int()? Not because the answer has a decimal point — it has one either way, since / always produces a float, even for 150 / 3. The reason is the user. You do not know whether they will type 50 or 50.5, and the two functions are not equally forgiving:
float() accepts everything int() accepts, and more. int() is the fussy one — it rejects any text with a decimal point in it, even '50.0'. So float() is the safer choice whenever the value could sensibly be either, which makes the program work for whoever runs it rather than only for the person who wrote it.
int() refusing 2.5 is the program protecting itself. For a measurement, a mark or an amount of money, reach for float().Try it with three marks of your own:
3Doing it in one line — carefully
You can write the calculation as a single line, and this is where the marks are lost. These two lines look almost identical and give completely different answers:
a = 40
b = 50
c = 60
wrong = a + b + c / 3
right = (a + b + c) / 3
print('wrong gives', wrong)
print('right gives', right)wrong gives 110.0 right gives 50.0
Division runs before addition, so the first line divides only c by 3 and then adds it to the other two. The brackets in the second line force the addition to happen first — which is what “the average of three numbers” actually means.
a + b + c / 3 is perfectly legal Python. It runs, it prints, and it is wrong. That makes it a logical error — the kind only you can catch. Test with three numbers whose average you already know (40, 50, 60 → 50) and a wrong answer stands out at once.4Now you try
The program below has the bug in it on purpose. Run it with 40, 50 and 60 — it will say 110.0. Fix the brackets so it says 50.0, then extend it to print the percentage as well (the total out of 300).
5Recap
(a + b + c) / 3 — the brackets are not decoration, because / runs before +. Splitting the work into total and then avg avoids the trap altogether and reads better.With a = 40, b = 50, c = 60, what does a + b + c / 3 print?
Why is float() the safer choice for reading these three marks?