Python While Loop Quiz (original) (raw)
What does the following Python code do?
Python `
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: 2"
How can you iterate over the items of a list using a while loop?
- Use the range function with the length of the list.
- Convert the list to a set and iterate over it.
- Use the enumerate function.
In Python, can a while loop be used to iterate over a dictionary directly?
- Only if the dictionary keys are integers.
- Only if the dictionary has a single key.
In Python, how can you emulate the behavior of a break statement inside a while loop without using bre
- Raise a custom exception.
In Python, can a while loop have multiple else blocks?
- Only if the loop has multiple conditions.
- Only if the loop uses nested if statements.
What is the purpose of the assert statement in a while 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.
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.
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.
What is the purpose of the continue statement in a while loop?
- Skips the remaining code in the loop and moves to the next iteration.
- Exits the loop prematurely.
- Breaks out of the loop entirely.
What is the output of the following Python code?
Python `
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.
There are 20 questions to complete.
Take a part in the ongoing discussion