Loops in Python - Quiz with answers
Take a quiz on Python loops. The questions cover various aspects such as for loops, while loops, control statements (break, continue), nested loops, and more.
Question 1.
What is the purpose of a loop in Python?
Question 2.
What are the two main types of loops in Python?
Question 3.
Write a for loop to print numbers from 10 down to 1 (inclusive) using at most 2-lines of code.
Your answer:
Question 4.
Write a while loop that is equivalent to your answer in Question 3 above. Use at most 4 lines of code.
Your answer:
Question 5.
Which of the following while loop headers will cause an infinity loop.?
Question 6.
Which of the following loops is the most appropriate when number of iterations is unknown beforehand?
Question 7.
What will be the output of the following code?
for n in range(2, 10, 2):
print(n, end = ' ')
Question 8.
What does the break
statement do in a loop?
Question 9.
What is the purpose of the continue
statement in a loop?
Question 10.
Write a for
loop that uses the continue
statement to print only the odd numbers from 0 to 10. Use at most 4 lines of code.
Your answer:
Question 11.
What is the output of the following code?
k = 1
while k < 10 :
print(k, end = ' ')
if k == 3:
break
k += 1
Question 12.
What is the output of the following code?
for i in range(5):
if i == 3:
break
else:
print("Loop completed")
Question 13.
What is the typical use of the pass
statement in loops?
Question 14.
What is the output of the following code?
for i in range(5):
pass
print(i)
Question 15.
How many times will "Hello"
be printed in the following code?
for i in range(3):
for j in range(4):
print("Hello")
Question 16.
Write a for
loop that outputs the following pattern.
*
**
***
****
*****
Use at most 4
lines of code.
Your answer:
Question 17.
Write a for loop that outputs the following pattern.
*****
****
***
**
*
Use at most 4
lines of code.
Your answer:
Question 18.
The following is a list whose elements are 2-length tuples. Each tuple contains a country and its capital
L = [('Japan', 'Tokyo'), ('Canada', 'Ottawa'), ('Finland', 'Helsinki'), ('Kenya', 'Nairobi')]
Using a for
loop, print each country and the capital in a single line with the format shown below:
Country, Capital
Country, Capital
...
Use at most 3 lines of code.
Your answer:
Question 19.
How many of these questions do you think you will get right?