Which is better?
Answers are for parents and teachers.
1
The requirements are: ask for a distance in kilometres and output it in miles (1 kilometre is about 0.6 miles). Write a plain version in Python. Then write a more robust version that rejects a distance below 0. What do they print for 10 and for −4?
Model answer. Plain version: km = float(input("Kilometres? ")) / print("Miles:", km * 0.6). Robust version (lines are separated by /, and [indent] means four spaces at the start of the line): km = float(input("Kilometres? ")) / if km >= 0: / [indent] print("Miles:", km * 0.6) / else: / [indent] print("Distance cannot be below 0"). Check: For 10 it prints Miles: 6.0. For −4 it prints Distance cannot be below 0, but the plain version would print Miles: -2.4.
2
This program asks for a word and prints twice its length. The user types tree. How many variables does it use? Rewrite it with fewer variables.
Python
1word = input("Word? ") 2length = len(word) 3doubled = length * 2 4print(doubled)
For tree it prints 8. It uses three variables: word, length and doubled. A shorter version is word = input("Word? ") / print(len(word) * 2), with one variable.
3
A program uses one variable but gives wrong answers. Another program uses three variables and works. A friend says the first is more efficient. Do you agree? Explain.
No. The first program fails the requirements, so it is not a solution at all. Only working programs are worth comparing for efficiency.
4
Two ways to collect homework from 20 pupils. Method A: the teacher walks to every desk. Method B: each row passes its books along to the front. Both collect all the books. Which uses fewer steps for the teacher? Write a verdict with one reason.
Method B. The teacher makes only a few steps to the front instead of 20 stops, and both methods meet the requirement. The reason is the smaller number of steps.
5
Rank the three programs from best to worst, with a reason for each place.
| Program | Requirements met | Robust? | Variables |
|---|---|---|---|
| X | 3 of 3 | no | 6 |
| Y | 3 of 3 | yes | 4 |
| Z | 3 of 3 | no | 4 |
Y is first: it is robust and has fewer variables than X. Z is second: it has 4 variables but is not robust. X is third: it is not robust and has 6 variables. The comparison is fair, because all three meet the requirements.