Cases and lists
Answers are for parents and teachers.
1
Write a program that asks for a colour and prints Stop if the user types red in any mix of capitals and small letters, and Go for anything else. What does it print for RED, Red and green?
Model answer (lines are separated by /, and [indent] means four spaces at the start of the line): colour = input("Colour? ").lower() / if colour == "red": / [indent] print("Stop") / else: / [indent] print("Go"). Check: It prints Stop for RED, Stop for Red and Go for green.
2
Give the value of "Go-Kart".upper(), "ABC123".lower() and "x".upper().
"GO-KART", "abc123" and "X". Symbols such as the hyphen and digits do not change.
3
The list is fruit = ["mango", "pear", "plum", "fig", "lime"]. Which items are fruit[2] and fruit[len(fruit) - 1]? How many items are there before and after fruit.append("kiwi")?
fruit[2] is plum, and fruit[len(fruit) - 1] is lime. There are 5 items before the append and 6 after it.
4
This program stops with an error. Give the message and correct the program.
Python
1items = [4, 6] 2for p in items: 3 total = total + p 4print(total)
NameError: name 'total' is not defined. The variable total is used before it has a value. Add total = 0 before the loop.
5
Give two differences between an array and a Python list, and one thing they have in common.
An array has a fixed size, and a list can grow and shrink. An array is created with a stated number of elements, but a list can start empty. In common: both store many items under one identifier and use an index that starts at 0.