Lecture
How to Execute a Loop While a Given Condition is True
The while loop repeatedly executes a block of code as long as the specified condition is True.
Structure of a while loop
while condition: code block
After the while keyword, you must specify a condition followed by a colon (:).
Code Example
The following example executes the code block until the condition counter < 5 becomes false, meaning until counter reaches 5.
Example of a while loop
counter = 0 # Repeat until the condition becomes False while counter < 5: print(counter) counter += 1 # Output: 0, 1, 2, 3, 4
By utilizing the while loop’s ability to repeat until a condition is met, you can continuously prompt the user for input until a specific message is entered.
Example of handling user input
# Variable to store user input user_input = "" # Repeat until the user enters 'exit' while user_input.lower() != "exit": # Receive user input user_input = input("Enter 'exit' to quit: ")
Lessons in this chapter · While Loops and List Comprehensions
- 1. How to Execute a Loop While a Given Condition is True
- 2. Controlling Logic Flow Inside Loops
- 3. Using While Loops with Lists
- 4. Multiple-choice quiz
- 5. Calculating Minimum, Maximum, and Sum
- 6. How to Reverse the Order of Objects
- 7. Iterating Over Elements of an Iterable
- 8. Iterating Over Key-Value Pairs with the items() Function
- 9. Simplifying Lists with List Comprehensions
- 10. Using the join() Function to Concatenate Strings
- 11. Differences Between Iterables and Iterators
- 12. Coding Quiz - Determine Odd/Even
- 13. Multiple-choice quiz
- 14. Fill-in-the-blank quiz
Quiz
0 / 1
You need to add a colon (:) after the condition in a while loop.
True
False
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help