Python: Loops, Lists and Functions: Unit Exam A
Instructions
- Time allowed
- 25 minutes
- Total marks
- 25
- Calculator
- No calculator is permitted.
- Answer all the questions.
Questions
for i in range(3):
print("Hi")- L3
range(3) gives 0, 1 and 2: three passes.
for i in range(1, 5):
print(i)- L4
range(1, 5) stops before 5, so the last value is 4.
total = 0
for n in range(1, 6):
total = total + n
print(total)- L15
1 + 2 + 3 + 4 + 5 = 15.
- Lred
- Lblue
- Lyellow
- L4
Indexes start at 0, so colours[0] is red and colours[2] is blue. -1 is the last item, yellow. There are 4 items.
Tick one box.
- LA colours.append("purple")
append() adds to the end. colours[4] would be an error, because the list has no index 4 yet.
Tick one box.
- LC A loop whose condition never becomes false, so it never stops
If nothing inside the loop ever makes the condition false, it runs for ever.
x = 1
while x < 50:
x = x * 2
print(x)- L64
x doubles: 2, 4, 8, 16, 32, 64. 64 is not below 50, so the loop stops and 64 is printed.
Tick one box.
- LB A while loop
A while loop repeats until its condition changes.
def double(n):
return n * 2
print(double(4) + double(3))- L14
double(4) returns 8 and double(3) returns 6: 8 + 6 = 14.
| Parameter | Function call | Return value | |
|---|---|---|---|
| n in def double(n): | |||
| double(4) | |||
| The value worked out by n * 2 and sent back |
Tick one box in each row.
- Ln in def double(n):: Parameter
- Ldouble(4): Function call
- LThe value worked out by n * 2 and sent back: Return value
n is the parameter, double(4) calls the function, and n * 2 is sent back as the return value.
def area(width, height):
# complete the function
pass
- LDefines a function called area with two parameters
- LReturns the correct area, for example 12 for a width of 3 and a height of 4
- LReturns the value rather than printing it
Multiply the width by the height and return the result.
def area(width, height):
return width * height- LChecking that input is sensible or follows the rules before it is used
- LA named check, such as a range, length, presence or type check
Validation is the program checking that input is sensible, and follows the rules, before using it. A range check, for example, rejects an age outside 11 to 18.
for i in range(2, 11, 4):
print(i)| Line | Printed |
|---|---|
| 1 | |
| 2 | |
| 3 |
- L2
- L6
- L10
range(2, 11, 4) starts at 2 and goes up in 4s, stopping before 11: 2, 6, 10.
Tick one box.
- LD 8
Index 1 is the second item, 8.
scores = [3, 7, 2]
scores.append(5)
print(len(scores))- L4
Appending 5 makes four items.