Python: Loops, Lists and Functions: Unit Exam B
Instructions
- Time allowed
- 25 minutes
- Total marks
- 25
- Calculator
- No calculator is permitted.
- Answer all the questions.
Questions
for i in range(5):
print(i)- L0
range(5) starts at 0.
- L6
2, 3, 4, 5, 6 and 7: six numbers, stopping before 8.
count = 10
while count > 0:
count = count - 3
print(count)- L-2
10, 7, 4, 1, then -2. -2 is not above 0, so the loop stops and prints -2.
- Lhamster
- Lrabbit
- L4
- Lcat
rabbit is added at index 3, and index 1 is replaced by hamster, giving cat, hamster, fish, rabbit.
Tick one box.
- LB for i in range(1, 11): print(i)
range(1, 11) starts at 1 and stops before 11.
n = int(input("Number: "))
# print the first five results of the n times table
- LUses a loop
- LPrints 3, 6, 9, 12 and 15 for 3
- LWorks for any number: 7, 14, 21, 28 and 35 for 7
Loop i from 1 to 5 with range(1, 6), printing i * n each time.
n = int(input("Number: "))
for i in range(1, 6):
print(i, "x", n, "=", i * n)Tick one box.
- LD The number of items in the list
len() counts the items.
def greet(name):
return "Hi " + name
message = greet("Ana")
print(message + "!")- LHi Ana!
greet returns Hi Ana, and the ! is added before printing.
Tick one box.
- LC A parameter is passed into a function; a return value is sent back out of it
Values go in through parameters and come out through return.
- LCode can be reused without writing it again
- LPrograms are easier to read, test and fix, because they are split into named parts
A function is written once and called whenever it is needed, so code is not repeated. Splitting a program into named functions also makes it easier to read, and each part can be tested and fixed on its own.
age = int(input("Age: "))
while age < 11 or age > 18:
print("Invalid")
age = int(input("Age: "))
print("Accepted")| Line | Output |
|---|---|
| 1 | |
| 2 | |
| 3 |
- LInvalid
- LInvalid
- LAccepted
9 is below 11, so Invalid. 25 is above 18, so Invalid. 14 is in range, so the loop ends and Accepted is printed.
Tick one box.
- LA Range check
A range check tests that a value lies between limits.
| for loop | while loop | |
|---|---|---|
| Print each item in a shopping list | ||
| Keep asking until the user types quit | ||
| Repeat exactly 20 times | ||
| Keep rolling a dice until it shows a six |
Tick one box in each row.
- LPrint each item in a shopping list: for loop
- LKeep asking until the user types quit: while loop
- LRepeat exactly 20 times: for loop
- LKeep rolling a dice until it shows a six: while loop
Use for when the number of repeats is known, and while when you repeat until something happens.
nums = [5, 10, 15]
total = 0
for n in nums:
total = total + n
print(total / len(nums))- L10
The total is 30 and there are 3 items: 30 / 3 = 10.0.