Chapter 8 Beginner 63 Questions

Practice Questions — Loops in Python (for and while)

← Back to Notes
9 Easy
13 Medium
11 Hard

Topic-Specific Questions

Question 1
Easy
What is the output of the following code?
for i in range(4):
    print(i)
range(4) generates numbers starting from 0 up to (but not including) 4.
0
1
2
3
Question 2
Easy
What is the output?
for i in range(1, 6):
    print(i, end=" ")
range(1, 6) starts at 1 and stops before 6.
1 2 3 4 5
Question 3
Easy
What is the output?
for char in "Hi":
    print(char)
A for loop iterates over each character of a string.
H
i
Question 4
Easy
What is the output?
count = 3
while count > 0:
    print(count)
    count -= 1
The loop runs while count is greater than 0, decreasing count each time.
3
2
1
Question 5
Easy
What is the output?
for i in range(2, 10, 3):
    print(i, end=" ")
range(2, 10, 3) starts at 2 and adds 3 each time, stopping before 10.
2 5 8
Question 6
Easy
What is the output?
for i in range(3):
    print("Hello")
The loop runs 3 times. The value of i is not used in the body.
Hello
Hello
Hello
Question 7
Medium
What is the output?
for i in range(5, 0, -1):
    print(i, end=" ")
Negative step counts backwards. The stop value (0) is excluded.
5 4 3 2 1
Question 8
Medium
What is the output?
total = 0
for i in range(1, 6):
    total += i
print(total)
The loop adds 1 + 2 + 3 + 4 + 5 to total.
15
Question 9
Medium
What is the output?
x = 1
while x < 20:
    x *= 2
print(x)
Trace x: 1, 2, 4, 8, 16, ... What happens when x reaches 16?
32
Question 10
Medium
What is the output?
for i in range(3):
    for j in range(2):
        print(i, j)
The inner loop runs completely for each iteration of the outer loop.
0 0
0 1
1 0
1 1
2 0
2 1
Question 11
Medium
What is the output?
for i in range(1, 5):
    print("*" * i)
The * operator on strings repeats the string. "*" * 3 gives "***".
*
**
***
****
Question 12
Medium
What is the output?
for i in range(10, 0):
    print(i)
What is the default step? Can you count from 10 to 0 with a positive step?
(No output - nothing is printed)
Question 13
Medium
What is the output?
for i in range(3):
    for j in range(3):
        if i == j:
            print(1, end=" ")
        else:
            print(0, end=" ")
    print()
This prints 1 when the row equals the column (diagonal), and 0 otherwise.
1 0 0
0 1 0
0 0 1
Question 14
Hard
What is the output?
for i in range(5):
    pass
print(i)
pass does nothing, but the loop still runs. What value does i hold after the loop?
4
Question 15
Hard
What is the output?
for i in range(3):
    for j in range(i + 1):
        print(i + j, end=" ")
    print()
Trace each row: when i=0, j goes to 1. When i=1, j goes to 2. When i=2, j goes to 3.
0
1 2
2 3 4
Question 16
Hard
What is the output?
x = 100
while x > 1:
    x //= 3
    print(x, end=" ")
Floor divide x by 3 each time: 100 // 3 = ?, then that // 3 = ?, and so on.
33 11 3 1 0
Question 17
Hard
What is the output?
for i in range(4):
    for j in range(4 - i):
        print("*", end="")
    print()
When i=0, the inner loop runs 4 times. When i=1, it runs 3 times. And so on.
****
***
**
*
Question 18
Hard
What is the output?
result = 1
for i in range(1, 6):
    result *= i
print(result)
This calculates the factorial of 5 (1 * 2 * 3 * 4 * 5).
120
Question 19
Hard
What is the output?
for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end="\t")
    print()
This prints a 3x3 multiplication table. The tab character \t aligns columns.
1 2 3
2 4 6
3 6 9
Question 20
Medium
What is the difference between a for loop and a while loop in Python? When would you choose one over the other?
Think about whether you know the number of iterations in advance.
A for loop is used when you know how many times to iterate or when iterating over a sequence (string, list, range). A while loop is used when you want to repeat as long as a condition is True, and you may not know the number of iterations in advance. Use for when counting or traversing sequences. Use while when waiting for a condition to change (like user input or a calculation reaching a threshold).

Mixed & Application Questions

Question 1
Easy
What is the output?
word = "Code"
for ch in word:
    print(ch, end="-")
The loop iterates over each character and prints it followed by a hyphen.
C-o-d-e-
Question 2
Easy
What is the output?
for num in [10, 20, 30]:
    print(num + 5)
The loop iterates over the list. Each element has 5 added to it.
15
25
35
Question 3
Easy
What is the output?
i = 5
while i > 0:
    i -= 2
print(i)
Trace i: 5 -> 3 -> 1 -> ? What happens when i becomes negative?
-1
Question 4
Medium
What is the output?
for i in range(1, 4):
    for j in range(1, 4):
        if i != j:
            print(i, j)
This prints all (i, j) pairs where i and j are different.
1 2
1 3
2 1
2 3
3 1
3 2
Question 5
Medium
What is the output?
nums = [4, 7, 2, 9, 1]
max_val = nums[0]
for num in nums:
    if num > max_val:
        max_val = num
print("Max:", max_val)
This finds the maximum value by comparing each element with the current maximum.
Max: 9
Question 6
Medium
What is the output?
for i in range(3):
    print(i, end=" ")
    for j in range(3):
        print(j, end=" ")
    print()
The outer print and inner loop are at the same indentation level inside the outer loop.
0 0 1 2
1 0 1 2
2 0 1 2
Question 7
Medium
What is the output?
for index, val in enumerate(["a", "b", "c"], start=1):
    print(index, val)
enumerate() returns (index, value) pairs. start=1 makes the index begin at 1.
1 a
2 b
3 c
Question 8
Hard
What is the output?
n = 1
while n < 100:
    n *= 3
print(n)
Trace n: 1, 3, 9, 27, 81, ... When does n first reach or exceed 100?
243
Question 9
Hard
What is the output?
for i in range(4):
    for j in range(i, 4):
        print(j, end=" ")
    print()
The inner loop starts from i (not 0) each time. When i increases, the inner loop starts later.
0 1 2 3
1 2 3
2 3
3
Question 10
Hard
What is the output?
count = 0
for i in range(5):
    for j in range(5):
        if i + j == 4:
            count += 1
print(count)
Count pairs (i, j) where i + j equals 4, with both i and j in range(5).
5
Question 11
Medium
What does the else clause on a for loop do? When does it execute and when does it NOT execute?
Think about what happens when a loop is stopped early versus when it finishes all iterations.
The else clause on a loop runs only when the loop completes all its iterations normally. It does NOT run if the loop is terminated early by a break statement. If the loop body never executes (e.g., for i in range(0)), the else block still runs because no break was encountered.
Question 12
Hard
What is the output?
for i in range(3):
    for j in range(3):
        print("(", i, ",", j, ")", end=" ")
    print()
This prints all (row, column) coordinates of a 3x3 grid.
( 0 , 0 ) ( 0 , 1 ) ( 0 , 2 )
( 1 , 0 ) ( 1 , 1 ) ( 1 , 2 )
( 2 , 0 ) ( 2 , 1 ) ( 2 , 2 )
Question 13
Hard
What is the output?
s = "Python"
for i in range(len(s) - 1, -1, -1):
    print(s[i], end="")
len("Python") is 6. range(5, -1, -1) gives 5, 4, 3, 2, 1, 0. This accesses characters in reverse.
nohtyP

Multiple Choice Questions

MCQ 1
What does range(5) generate?
  • A. 1, 2, 3, 4, 5
  • B. 0, 1, 2, 3, 4
  • C. 0, 1, 2, 3, 4, 5
  • D. 1, 2, 3, 4
Answer: B
B is correct. range(5) generates numbers starting from 0 up to but not including 5: 0, 1, 2, 3, 4 (five numbers). Option A starts from 1 and includes 5. Option C has 6 numbers. Option D has only 4 numbers.
MCQ 2
How many times does this loop run? for i in range(1, 8):
  • A. 8 times
  • B. 7 times
  • C. 9 times
  • D. 6 times
Answer: B
B is correct. range(1, 8) generates 1, 2, 3, 4, 5, 6, 7 (seven numbers). The stop value 8 is excluded. A quick way to count: 8 - 1 = 7.
MCQ 3
Which loop is best when you know exactly how many times you want to repeat?
  • A. while loop
  • B. for loop
  • C. do-while loop
  • D. infinite loop
Answer: B
B is correct. A for loop with range() is ideal when the number of iterations is known. A while loop (option A) is better for condition-based repetition. Python does not have a do-while loop (option C). An infinite loop (option D) is not a type; it is a bug.
MCQ 4
What is the output of: for i in range(0): print(i)
  • A. 0
  • B. Nothing is printed
  • C. Error
  • D. Infinite loop
Answer: B
B is correct. range(0) generates an empty sequence (zero numbers). The loop body never executes, so nothing is printed. This is not an error; it is valid code.
MCQ 5
What keyword is used to skip to the next iteration of a loop?
  • A. break
  • B. skip
  • C. continue
  • D. next
Answer: C
C is correct. The continue statement skips the rest of the current iteration and moves to the next one. break (option A) exits the loop entirely. skip (option B) and next (option D) are not Python keywords.
MCQ 6
What does range(10, 2, -3) generate?
  • A. 10, 7, 4
  • B. 10, 7, 4, 1
  • C. 10, 7, 4, 2
  • D. 10, 8, 5, 2
Answer: A
A is correct. Starting at 10, subtracting 3 each time: 10, 7, 4. The next would be 1, but we stop before reaching 2 (actually 1 < 2 when going backwards means stop). Wait - let us re-check: 4 - 3 = 1. Since 1 < 2 (stop value) with negative step, 1 is not included. So the answer is 10, 7, 4.
MCQ 7
How many total iterations does this nested loop have? for i in range(5): for j in range(3):
  • A. 5
  • B. 3
  • C. 8
  • D. 15
Answer: D
D is correct. The outer loop runs 5 times and for each outer iteration, the inner loop runs 3 times. Total iterations of the inner body: 5 * 3 = 15. Options A and B only count one of the loops. Option C adds them instead of multiplying.
MCQ 8
What happens if the while loop condition is False from the start?
  • A. The loop runs once
  • B. The loop body never executes
  • C. Python raises an error
  • D. The loop runs forever
Answer: B
B is correct. A while loop checks the condition BEFORE executing the body. If the condition is False initially, the body is skipped entirely. This is different from a do-while loop (which Python does not have), where the body always runs at least once (option A).
MCQ 9
What is the value of i after this loop? for i in range(10): pass
  • A. 10
  • B. 9
  • C. 0
  • D. i is undefined
Answer: B
B is correct. The loop variable i takes values 0 through 9. After the loop completes, i retains its last value, which is 9. In Python, loop variables are NOT scoped to the loop. Option D would be true in some other languages but not Python.
MCQ 10
What does enumerate() return?
  • A. Only the index of each element
  • B. Only the value of each element
  • C. Pairs of (index, value)
  • D. The total count of elements
Answer: C
C is correct. enumerate() returns pairs of (index, value) for each element in the sequence. This allows you to access both the position and the value in a single loop. Options A and B only give one piece of information. Option D describes len().
MCQ 11
When does the else clause of a for loop execute?
  • A. When the loop encounters an error
  • B. When the loop is stopped by break
  • C. When the loop completes without break
  • D. On every iteration of the loop
Answer: C
C is correct. The else block runs only when the loop finishes all iterations without encountering a break. If break is executed (option B), the else block is skipped. It is not related to errors (option A) and does not run on every iteration (option D).
MCQ 12
What is the output of: for i in range(3, 3): print(i)
  • A. 3
  • B. Nothing is printed
  • C. Error
  • D. 0 1 2
Answer: B
B is correct. range(3, 3) generates an empty sequence because the start and stop are the same (there are no numbers >= 3 and < 3). The loop body never executes. This is not an error (option C); it is valid Python.
MCQ 13
What is the output of this code?
x = 10
while x > 0:
    x -= 3
print(x)
  • A. 1
  • B. 0
  • C. -2
  • D. 3
Answer: C
C is correct. x starts at 10: 10->7->4->1. After x=1, the condition 1 > 0 is True, so x becomes 1-3 = -2. Now -2 > 0 is False, loop stops. x = -2. Option A (1) would be correct if the check happened after the subtraction.
MCQ 14
How many times does the inner print execute?
for i in range(4):
    for j in range(i):
        print(i, j)
  • A. 16
  • B. 10
  • C. 6
  • D. 4
Answer: C
C is correct. When i=0: range(0) gives 0 iterations. When i=1: range(1) gives 1 iteration. When i=2: range(2) gives 2 iterations. When i=3: range(3) gives 3 iterations. Total: 0 + 1 + 2 + 3 = 6.
MCQ 15
What is the output?
for i in range(3):
    print(i)
else:
    print("Done")
  • A. 0 1 2
  • B. 0 1 2 Done
  • C. Done
  • D. Error - else cannot be used with for
Answer: B
B is correct. The loop prints 0, 1, 2 (each on a new line). Since the loop completes without a break, the else block executes and prints "Done". Option D is wrong because Python does support else with for loops.
MCQ 16
Which creates the sequence 20, 15, 10, 5?
  • A. range(20, 0, -5)
  • B. range(20, 4, -5)
  • C. range(20, 5, -5)
  • D. range(5, 20, 5)
Answer: B
B is correct. range(20, 4, -5) starts at 20, subtracts 5 each time, and stops before 4: 20, 15, 10, 5. The next would be 0, but 0 < 4 (in terms of going below stop), so it stops. Option A would include 5 and then stop. Option C would include 5 only if stop is less than 5. Option D counts upward.
MCQ 17
What causes an infinite while loop?
  • A. Using a very large range
  • B. The condition never becoming False
  • C. Using nested loops
  • D. Forgetting the colon after while
Answer: B
B is correct. A while loop becomes infinite when its condition never becomes False, usually because the loop variable is not updated or updated incorrectly. A large range (option A) makes a long loop, not infinite. Nested loops (option C) are normal. Missing colon (option D) causes a SyntaxError, not an infinite loop.
MCQ 18
What does end="" do in print()?
  • A. Ends the program
  • B. Prints nothing after the value (no newline)
  • C. Prints an empty string
  • D. Causes an error
Answer: B
B is correct. By default, print() adds a newline after the output. end="" replaces that newline with nothing, so the next print continues on the same line. This is commonly used in loops to print values side by side.
MCQ 19
What is the output of: print(list(range(1, 10, 2)))?
  • A. [1, 3, 5, 7, 9]
  • B. [1, 3, 5, 7]
  • C. [2, 4, 6, 8]
  • D. [1, 2, 3, 4, 5, 6, 7, 8, 9]
Answer: A
A is correct. range(1, 10, 2) starts at 1 and adds 2 each time, stopping before 10: 1, 3, 5, 7, 9. Converting to a list gives [1, 3, 5, 7, 9]. These are odd numbers from 1 to 9.
MCQ 20
What happens when you use range() with a step of 0?
  • A. It returns an empty range
  • B. It generates an infinite sequence
  • C. ValueError: range() arg 3 must not be zero
  • D. It uses step 1 as default
Answer: C
C is correct. A step of 0 would create an infinite sequence (never progressing), so Python raises a ValueError to prevent this. The error message is: "range() arg 3 must not be zero". This is a safety feature.

Coding Challenges

Challenge 1: Sum of Even Numbers

Easy
Write a program that uses a for loop to calculate and print the sum of all even numbers from 2 to 20 (inclusive).
Sample Input
(No input required)
Sample Output
Sum of even numbers from 2 to 20: 110
Use a for loop with range(). Do not hardcode the answer.
total = 0
for i in range(2, 21, 2):
    total += i
print("Sum of even numbers from 2 to 20:", total)

Challenge 2: Reverse a String Using a Loop

Easy
Aarav has the string "Python". Write a program using a for loop to print the string in reverse order (character by character on the same line).
Sample Input
(No input required)
Sample Output
nohtyP
Use a for loop. Do not use slicing ([::-1]).
text = "Python"
for i in range(len(text) - 1, -1, -1):
    print(text[i], end="")
print()

Challenge 3: Multiplication Table

Easy
Write a program that prints the multiplication table of 7 (from 7 x 1 to 7 x 10).
Sample Input
(No input required)
Sample Output
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 7 x 6 = 42 7 x 7 = 49 7 x 8 = 56 7 x 9 = 63 7 x 10 = 70
Use a for loop with range().
num = 7
for i in range(1, 11):
    print(num, "x", i, "=", num * i)

Challenge 4: Count Vowels in a String

Medium
Priya has the string "Modern Age Coders". Write a program that counts and prints the number of vowels (a, e, i, o, u - both uppercase and lowercase) in the string.
Sample Input
(No input required)
Sample Output
Vowels in 'Modern Age Coders': 6
Use a for loop to iterate through each character.
text = "Modern Age Coders"
count = 0
for ch in text:
    if ch.lower() in "aeiou":
        count += 1
print("Vowels in '" + text + "':", count)

Challenge 5: Fibonacci Sequence

Medium
Write a program that prints the first 10 numbers of the Fibonacci sequence. The sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34.
Sample Input
(No input required)
Sample Output
0 1 1 2 3 5 8 13 21 34
Use a while or for loop.
a = 0
b = 1
for i in range(10):
    print(a, end=" ")
    a, b = b, a + b
print()

Challenge 6: Number Guessing Simulation

Medium
Rohan is building a number guessing game. The secret number is 7. Simulate guesses using a while loop: start with guess = 1 and increase by 2 each time until the guess equals the secret number. Print each guess and whether it is too low, too high, or correct.
Sample Input
(No input required)
Sample Output
Guess: 1 - Too low! Guess: 3 - Too low! Guess: 5 - Too low! Guess: 7 - Correct!
Use a while loop. Do not use a for loop.
secret = 7
guess = 1
while guess <= secret:
    if guess < secret:
        print("Guess:", guess, "- Too low!")
    else:
        print("Guess:", guess, "- Correct!")
    guess += 2

Challenge 7: Prime Number Checker

Hard
Write a program that checks whether the number 29 is prime. A prime number is only divisible by 1 and itself. Use a for loop to test divisibility and print the result.
Sample Input
(No input required)
Sample Output
29 is a prime number
Use a for loop with a break statement. Use the loop-else pattern.
num = 29
if num < 2:
    print(num, "is not a prime number")
else:
    for i in range(2, num):
        if num % i == 0:
            print(num, "is not a prime number")
            break
    else:
        print(num, "is a prime number")

Challenge 8: Nested Loop Grid with Coordinates

Hard
Write a program that prints a 4x4 grid where each cell shows its row and column number in the format (row,col), with rows and columns numbered from 1.
Sample Input
(No input required)
Sample Output
(1,1) (1,2) (1,3) (1,4) (2,1) (2,2) (2,3) (2,4) (3,1) (3,2) (3,3) (3,4) (4,1) (4,2) (4,3) (4,4)
Use nested for loops.
for i in range(1, 5):
    for j in range(1, 5):
        print("(" + str(i) + "," + str(j) + ")", end=" ")
    print()

Challenge 9: Digit Sum Calculator

Hard
Write a program using a while loop to calculate the sum of digits of the number 98764. Extract digits one by one using % and // operators.
Sample Input
(No input required)
Sample Output
Sum of digits of 98764: 34
Use a while loop with % and // operators. Do not convert to a string.
num = 98764
original = num
total = 0
while num > 0:
    digit = num % 10
    total += digit
    num //= 10
print("Sum of digits of", original, ":", total)

Challenge 10: Diamond Top Half

Hard
Write a program using nested loops to print the top half of a diamond with 5 rows. Each row should have leading spaces followed by stars.
Sample Input
(No input required)
Sample Output
* * * * * * * * * * * * * * *
Use nested for loops. Print spaces before stars.
n = 5
for i in range(1, n + 1):
    for j in range(n - i):
        print(" ", end="")
    for j in range(i):
        print("* ", end="")
    print()

Need to Review the Concepts?

Go back to the detailed notes for this chapter.

Read Chapter Notes

Want to learn Python with a live mentor?

Explore our Python course