Python while Loop
In control structures, such as the while loop, the execution of code can be repeated for as long as the condition is true. It is one of the fundamental control structures that let Python do repetitive work.
Syntax of the while loop
while condition:
# Code to execute as long as the condition is True
Key Components
condition:
- A condition is a logical expression with an outcome of either
TrueorFalse. - While this condition is true, the loop will continue executing.
2. Body of the while Loop:
- A series of commands that are executed repeatedly.
- Indentation is used to guide execution.
3. Loop Termination:
- The loop would stop executing once the condition gets
False.
Flowchart
- Evaluate the condition:
- If
True, then execute the body of the loop. - If
False, then exit the loop and move to the next line of code.
2. After every iteration, the condition is checked again.
Example 1: Simple Counter
count = 0
while count < 5:
print("Count is:", count)
count += 1 # Increment count to avoid infinite loop
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Explanation:
- It starts from
count = 0. - The loop condition
count < 5isTrue, so it executes the loop body. - The value of
countis incremented by 1 in each iteration. - The moment the
countreaches 5, the condition turnsFalseand the loop exists.
Potential Issues
Infinite Loops:
- If the condition is always True, then the loop will never stop.
- Example:
while True:
print("This will run forever!")
- To prevent this, ensure the condition eventually becomes
False.
Forgotten Updates:
- Failure to change variables associated with the condition may lead to infinite loops.
- Always ensure that the condition is updated appropriately within the loop.
Example 2: Using break to Exit the Loop
i = 0
while i < 10:
print("Number:", i)
if i == 5:
break # Exit the loop when i is 5
i += 1
Output:
Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Example 3: Using continue to Skip an Iteration
i = 0
while i < 5:
i += 1
if i == 3:
continue # Skip the rest of the code for this iteration
print("Number:", i)
Output:
Number: 1
Number: 2
Number: 4
Number: 5
Explanation:
- The
continuestatement skips the rest of the loop body and proceeds to the next iteration.
Example 4: Using else with a while Loop
x = 0
while x < 3:
print("Value of x:", x)
x += 1
else:
print("Loop finished")
Output:
Value of x: 0
Value of x: 1
Value of x: 2
Loop finished
Real -World Use Case: User Input
password = ""
while password != "1234":
password = input("Enter the password: ")
if password == "1234":
print("Access granted")
else:
print("Wrong password, try again")
Key Takeaways
- The
whileloop is useful for repeating tasks when the number of iterations is not known beforehand. - Always ensure the condition eventually becomes
Falseto avoid infinite loops. - Use
breakto get out of the loop early andcontinueto skip parts of the loop.