This lesson on Python While Loops is hands-on and example-driven. You will learn how to use Python's while loop to repeatedly execute a block of code until a specific condition is met. This is essential for robust data analytics applications, particularly for continuously validating user input until it meets required criteria.
What You'll Be Able To Do
- Construct a basic
whileloop that executes code based on a boolean condition. - Implement input validation by continually re-prompting a user until valid data is entered.
- Prevent infinite loops by ensuring the loop condition changes within the loop body.
- Utilize the
notoperator to continue a loop until a specific exit character is pressed. - Combine multiple conditions using the
oroperator within a loop header.
Detailed Concept Walkthrough
1. Basic While Loop Structure
A while loop repeatedly executes a code block as long as its controlling condition evaluates to True. It provides a mechanism for indefinite iteration, unlike for loops which iterate over sequences.
- Execution Flow: Python checks the condition; if True, the body executes. After the body finishes, the condition is checked again.
- Syntax Rule: The loop header ends with a colon (
:) and the body must be indented. - Mechanism: The loop continues until the condition evaluates to
False, at which point program execution resumes immediately after the loop body. - Best Practice: Always ensure that some operation inside the loop body modifies the variables used in the condition.
name = ""
while name == "":
name = input("Enter your name: ")
print(f"Hello {name}")
Key Takeaway: The loop condition must eventually become false to avoid an infinite loop.
2. Input Validation and Escaping
While loops are ideal for verifying user input, forcing the user to re-enter data until it satisfies specific requirements (e.g., positive number, non-empty string). This requires a clear exit strategy.
- Best Practice: Initialize the input variable before the loop so the condition can be checked initially.
- Mechanism: If the input is invalid (e.g.,
age < 0), the loop body prints an error message and re-prompts the user for a new value. - Under the Hood: The loop only terminates when the user provides input that makes the condition false, effectively giving the user a chance to 'escape'.
- Execution Flow: If you fail to re-prompt the user inside the loop, the condition variable never changes, resulting in an infinite loop.
age = int(input("Enter your age: "))
while age < 0:
print("Age can't be negative")
age = int(input("Enter your age: ")) # Re-prompt
print(f"You are {age} years old")
Key Takeaway: Always re-prompt the user inside the loop to give them a chance to correct the invalid input and escape.
3. Controlling Loops with Logic
Logical operators (not, or) allow complex conditions to control loop execution, enabling checks against multiple invalid states or defining exit criteria based on negation.
- Syntax Rule: Use
while not conditionto continue the loop until the condition becomes true (e.g., continuing until the user does press 'Q'). - Mechanism: The
oroperator keeps the loop running if any of the combined conditions are true (e.g.,while num < 1 or num > 10). - Best Practice: Structure complex conditions clearly to define the exact boundaries of valid input.
- Nuance: When using
or, only one side needs to be true for the loop to continue; the loop stops only when all conditions are false.
# Continue until Q is pressed
food = input("Enter food (Q to quit): ")
while not food == 'Q':
print(f"You like {food}")
food = input("Enter another food: ")
Key Takeaway: Logical operators define the precise boundaries that must be crossed for the loop to terminate.
Topics Covered in Python While Loops
- While Loop Definition (0:00 - 0:15) — A while loop executes code repeatedly while a condition remains true.
- If vs While (0:15 - 0:55) — Unlike an if statement, a while loop can continually prompt the user until valid input is provided.
- Infinite Loop Danger (0:55 - 1:45) — If the condition variable is not updated inside the loop, the program gets stuck in an infinite loop with no exit strategy.
- Input Validation Example (1:45 - 2:40) — A while loop is used to ensure a user enters a positive age, re-prompting if the input is negative.
- Using NOT Operator (2:40 - 3:45) — The
notlogical operator can be used to continue the loop until a specific quit character is entered. - Using OR Operator (3:45 - 4:40) — The
orlogical operator allows the loop to continue if the number is outside a valid range. - Summary and Use Case (4:40 - 5:00) — While loops are extremely useful for verifying user input and re-prompting for invalid data.
Python Cheat Sheet
-
while condition:— Executes code repeatedly while condition is Truewhile name == "": name = input("Name: ") -
while not condition:— Continues loop until condition becomes Truewhile not food == 'Q': food = input("Food: ") -
or— Logical operator; True if either condition is Truewhile num < 1 or num > 10: num = int(input("Num: ")) -
Infinite Loop— Loop condition never becomes Falsewhile True: print("Stuck")
Comparison Table
| Feature | If Statement | While Loop |
|---|---|---|
| Purpose | Conditional execution | Repetitive execution |
| Execution Count | Executes at most once | Executes zero to infinite times |
| Exit Strategy | Implicit (runs once) | Must be explicitly coded |
Common Pitfalls
- Mistake: Forgetting to update the variable controlling the loop condition. Avoid: Ensure the loop body contains code that eventually makes the condition False.
- Mistake: Not re-prompting the user inside an input validation loop.
Avoid: Always include the
input()function again within the loop body. - Mistake: Assuming the loop will exit without a clear exit condition. Avoid: Design the loop condition and body together to guarantee termination.
FAQs
- What is an infinite loop?
An infinite loop occurs when the condition controlling the
whileloop never evaluates toFalse, causing the program to run indefinitely. - Why use a
whileloop instead of anifstatement for input validation? Anifstatement checks the condition only once; awhileloop forces the user to re-enter input repeatedly until the condition is satisfied. - How do I stop an infinite loop in the console?
You typically press
Ctrl+C(orCmd+Con Mac) to send an interrupt signal to the running Python process.