About Lesson
The while
loop in Python is a control flow statement that allows code to be executed repeatedly based on a given condition. It’s especially useful when the number of iterations is not known in advance.
Syntax of a While Loop
while condition:
# Code block to execute
condition
: The loop will keep executing as long as this condition isTrue
.- The code inside the loop should eventually make the condition
False
to avoid an infinite loop.
How a While Loop Works
- The condition is checked first.
- If the condition is
True
, the code inside the loop runs. - After each iteration, the condition is checked again.
- When the condition becomes
False
, the loop stops.
Example 1: Basic While Loop
count = 1 # Initialization
while count <= 5: # Condition
print("Count:", count)
count += 1 # Update the variable
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Explanation:
- The loop starts with
count = 1
. - Each time the loop runs,
count
is incremented by 1. - The loop stops when
count > 5
.
Example 2: Using a While Loop for User Input
password = "" # Initialize variable
while password != "1234": # Condition
password = input("Enter the correct password: ")
print("Access granted!")
Output (Example Input):
Enter the correct password: 5678
Enter the correct password: 1234
Access granted!
Explanation:
- The loop keeps asking for input until the user enters the correct password.
Example 3: Breaking Out of a While Loop
Sometimes, you might need to exit a loop prematurely using the break
statement.
while True: # Infinite loop
num = int(input("Enter a positive number (or -1 to stop): "))
if num == -1: # Break condition
print("Exiting the loop!")
break
print(f"You entered: {num}")
Output (Example Input):
Enter a positive number (or -1 to stop): 5
You entered: 5
Enter a positive number (or -1 to stop): -1
Exiting the loop!
Example 4: Using a While Loop with Else
The else
block runs when the loop condition becomes False
.
counter = 1
while counter <= 3:
print("Counter:", counter)
counter += 1
else:
print("Loop ended!")
Output:
Counter: 1
Counter: 2
Counter: 3
Loop ended!
Explanation:
- The
else
block runs after the loop ends naturally.
Key Points to Remember
- The
while
loop is ideal for scenarios where you don’t know the number of iterations in advance. - Always update variables inside the loop to prevent infinite loops.
- Use
break
to exit a loop early andelse
to run code after the loop ends.