Question 1Easy4 marks
A program should compare two numbers and state their average and whether they are the same. The program below does this, but it contains errors.
01 # Average of two numbers
02 # Works out the average of two numbers and compares them
03 print("Number comparison tool")
04 print("------------------------")
05 num1 = int(input("Enter first number: "))
06 num2 = int(input("Enter second number: "))
07 average = num1 + num2 / 2
08 print("Number 1:", num1)
09 print("Number 2:", num2)
10 print("The average is", average)
11 if num1 = num2:
12 print("The numbers are the same")
13 else:
14 print("The numbers are different")
15 print("Thank you for using the tool")(a) Amend the program to:
- fix the syntax error on line 11
- fix line 07 so that the average is correctly calculated as (num1 + num2) ÷ 2.
(b) Once the syntax error is fixed but before line 07 is corrected, the program outputs
The average is 7.0 for the numbers 4 and 6. Explain why.[2]Show the answer and mark scheme
(a) Answer:
# Average of two numbers
# Works out the average of two numbers and compares them
print("Number comparison tool")
print("------------------------")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
average = (num1 + num2) / 2
print("Number 1:", num1)
print("Number 2:", num2)
print("The average is", average)
if num1 == num2:
print("The numbers are the same")
else:
print("The numbers are different")
print("Thank you for using the tool")- line 11: changes
=to== - line 07: adds brackets,
(num1 + num2) / 2
(b) Answer: Division has a higher precedence than addition, so
num2 / 2 is worked out first: 4 + 6 ÷ 2 = 4 + 3 = 7.0.- division (
/) is carried out before addition (+), because it has a higher precedence - so the program works out 4 + (6 ÷ 2) = 4 + 3 = 7.0 instead of (4 + 6) ÷ 2 = 5.0