Computer Science A Level (9618) Worksheet
Topic: While Loop in Python
Question 1: Write a Python `while` loop that prints numbers from 1 to 5.
Answer:
i=1
while i <= 5:
print(i)
i += 1
Explanation: The variable `i` starts at 1. The loop condition checks if `i <= 5`, and on each iteration, `i` is
printed and incremented. The loop stops when `i` becomes 6.
Question 2: What is the output of the following code?
```python
x=3
while x > 0:
print(x)
x -= 1
```
Answer:
Explanation: The loop starts with `x = 3`. Each iteration prints `x` and then decreases it by 1. The loop stops
when `x` becomes 0.
Question 3: Correct the error in this code snippet:
```python
n=1
while n < 5:
print(n)
n += 1
```
Answer:
n=1
while n < 5:
print(n)
n += 1
Explanation: Indentation is missing for the loop body. Python requires consistent indentation inside blocks
such as loops.
Question 4: Write a `while` loop that keeps asking the user to enter a number until they enter
0.
Answer:
num = int(input("Enter a number: "))
while num != 0:
num = int(input("Enter a number: "))
Explanation: The loop continues as long as the entered number is not 0. Once the user enters 0, the
condition becomes false, and the loop ends.
Question 5: Explain what this loop does:
```python
count = 10
while count >= 1:
print(count, end=" ")
count -= 1
```
Answer:
It prints numbers from 10 to 1 in the same line.
Explanation: The loop starts from 10 and decrements `count` by 1 each time, stopping at 0. `end=" "` prints
the output on the same line with spaces.
Question 6: Write a Python `while` loop that prints only even numbers between 1 and 10.
Answer:
i=2
while i <= 10:
print(i)
i += 2
Explanation: This loop starts at 2 and increases by 2 each time, which ensures only even numbers are
printed.
Question 7: What is the purpose of the `break` statement in a `while` loop? Demonstrate with
an example.
Answer:
i=1
while True:
print(i)
if i == 3:
break
i += 1
Explanation: Even though the condition is `True` (infinite loop), the loop stops when `i` becomes 3 because of
the `break` statement.
Question 8: How can you use a `while` loop to validate user input between 1 and 10?
Answer:
num = int(input("Enter a number between 1 and 10: "))
while num < 1 or num > 10:
num = int(input("Invalid! Enter a number between 1 and 10: "))
Explanation: The loop ensures the input is within the valid range. If not, the user is asked again until a valid
number is entered.
Question 9: Predict the output of the following code:
```python
x=1
while x < 10:
x += 3
print(x)
```
Answer:
10
Explanation: - First iteration: x = 1 -> x += 3 -> x = 4
- Second: x = 4 -> x = 7
- Third: x = 7 -> x = 10
After that, the loop exits since `x < 10` is false.
Question 10: Write a Python program using a `while` loop that sums numbers from 1 to 100.
Answer:
i=1
total = 0
while i <= 100:
total += i
i += 1
print("Sum:", total)
Explanation: This loop runs from 1 to 100, adding `i` to `total` each time. The result is the sum of the first 100
natural numbers.