Python While Loop Quiz

Last Updated :
Discuss
Comments

Question 1

What does the following Python code do?

count = 0
while count < 5:
   print("Count:", count)
   count += 1
   if count == 3:
       continue
   print("After Continue")
 

  • Prints "Count: 0" to "Count: 4" with "After Continue" after each line.

  • Prints "Count: 0" to "Count: 2" with "After Continue" after each line.

  • Prints "Count: 0" to "Count: 4" without "After Continue" after "Count: 3".

  • Raises a SyntaxError.

Question 2

How can you iterate over the items of a list using a while loop?

  • Use a for loop instead.

  • Use the range function with the length of the list.

  • Convert the list to a set and iterate over it.

  • Use the enumerate function.

Question 3

In Python, can a while loop be used to iterate over a dictionary directly?

  • Yes

  • No

  • Only if the dictionary keys are integers.

  • Only if the dictionary has a single key.

Question 4

 In Python, how can you emulate the behavior of a break statement inside a while loop without using bre

  • Use a return statement.

  • Use a pass statement.

  • Raise a custom exception.

  • Use a goto statement.

Question 5

In Python, can a while loop have multiple else blocks?

  • Yes

  • No

  • Only if the loop has multiple conditions.

  • Only if the loop uses nested if statements.

Question 6

What is the purpose of the assert statement in a while loop?

  • To terminate the loop.

  • To check if a condition is true and raise an error if not.

  • To skip the rest of the code in the loop.

  • It is not a valid statement in a while loop.

Question 7

What is the purpose of the else clause in a while loop?

  • It always runs after the loop completes.

  • It is used to handle exceptions within the loop.

  • It runs if the loop encounters an error.

  • It runs if the loop completes without encountering a break statement.

Question 8

How does the while-else construct work in Python?

  • It is not a valid construct in Python.

  • The else block always runs after the loop.

  • The else block runs if the loop encounters an error.

  • The else block runs if the loop completes without encountering a break statement.

Question 9

 What is the purpose of the continue statement in a while loop?

  • Terminates the loop.

  • Skips the remaining code in the loop and moves to the next iteration.

  • Exits the loop prematurely.

  • Breaks out of the loop entirely.

Question 10

What is the output of the following Python code?

num = 2
while num < 10:
   print(num, end=" ")
   num **= 2
 

  • Prints powers of 2 from 2 to 8.

  • Prints the square of numbers from 2 to 10.

  • Prints numbers in the range [2, 10) with a step of 2.

  • Raises a SyntaxError.

There are 20 questions to complete.

Take a part in the ongoing discussion