Stop the crash
Answers are for parents and teachers.
1
Say whether each is a syntax error, a logic error or a run-time error: (a) print(25 / 0) (b) a missing closing bracket in a print line (c) a change calculation that uses + where it should use − (d) int("1o") typed by the user.
(a) run-time. (b) syntax. (c) logic. (d) run-time: the letter o is not a digit, so the text cannot become a number.
2
The user types 3, and then another time 1. What happens each time? Explain, and write a repaired program.
Python
1prices = [3, 8, 5] 2choice = int(input("Item number (1 to 3)? ")) 3print("Price:", prices[choice])
With 3 the program stops with IndexError: list index out of range, because the list has positions 0, 1 and 2. With 1 it prints Price: 8, which is the second price, so this is a logic error as well. Repair: print(prices[choice - 1]) inside if choice >= 1 and choice <= 3:, with an else that prints a message.
3
A club asks for a username. It must be typed and have from 4 to 10 characters. Write the program in Python on paper, with a message for each problem.
name = input("Username? ") / if len(name) == 0: / print("Please type a username") / elif len(name) < 4: / print("Too short") / elif len(name) > 10: / print("Too long") / else: / print("Welcome,", name). Test 0, 3, 4, 10 and 11 characters.
4
Make a trace table with the columns water, days and Output. What does the program print? Does the loop end?
Python
1water = 1 2days = 0 3while water < 20: 4 water = water * 2 5 days = days + 1 6print(days)
water: 1, 2, 4, 8, 16, 32. days: 0, 1, 2, 3, 4, 5. When water is 32 the condition water < 20 is false, so the loop ends. It prints 5.
5
Explain in one sentence each what a syntax error, a logic error and a run-time error are, and give your own example of each.
A syntax error breaks the rules of the language and the program will not start, for example a missing colon. A logic error lets the program finish with a wrong answer, for example using < where <= is needed. A run-time error stops the program while it runs, for example int("cat").