Python while Loop
A while loop in Python repeatedly executes a block of code as long as a given condition is True.
Syntax
while condition:
# Code to execute while condition is true
Breakdown of Parts
while: The keyword that starts the loop.
condition: An expression that is evaluated before each iteration. If it is True, the code block inside the loop runs. It is False, the loop terminates.
Example: A loop that prints numbers from 1 to 3
counter = 1
while counter <= 3:
print(counter)
counter += 1
Output:
1
2
3
Here is how the while loop works step-by-step:
(1) First Iteration: The loop checks the condition counter <= 3. Since counter is 1, the condition is True. The code inside the loop executes and prints 1. Then the statement counter += 1 increases counter by 1, making its value 2. (counter += 1 is shorthand for counter = counter + 1).
(2) Second Iteration: The loop checks the condition counter <= 3 again. Now the counter is 2, so 2 <= 3 is still True. The code inside the loop executes and prints 2. Then the statement counter += 1 increases the counter by 1 again, making its value 3.
(3) Third Iteration: The loop checks the condition counter <= 3 again. Now the counter is 3, so 3 <= 3 is still True. The code inside the loop executes and prints 3. Then the statement counter += 1 increases the counter by 1 again, making its value 4.
(4) End of loop: The loop checks the condition counter <= 3 again. Now the counter is 4, so 4 <=3 is False. The loop terminates.
Example: Password Verification
Let’s ask the user to enter the password until it is correct.
password = "python123"
user_input = ""
while user_input != password:
user_input = input("Enter the password: ")
print("Access Granted")
Control Statements
You can control the flow of while loop using the break and continue statements.
The break Statement
The break statement immediately exits the loop, regardless of the loop’s condition.
For example:
# A loop that exits when it finds number 3
num = 0
while num < 10:
print(num)
if num == 3:
break # Exit the loop now
num += 1
print("Broke out of the loop")
Output:
0
1
2
3
Broke out of the loop
The continue Statement
The continue statement immediately skips the rest of the code inside the current iteration and proceeds directly to the next condition check.
For example:
# A loop that skips printing the number 3
num = 0
while num < 5:
num += 1
if num == 3:
continue
print(num)
Output:
1
2
4
5
In this example, when num equals 3, the continue statement causes Python to skip the print(num) statement and go straight to checking the condition num < 5 for the next iteration.
else in while Loop
The else block runs only if the while loop terminates normally, meaning the condition becomes False. It doesn’t run if the loop is exited using the break statement.
For example:
i = 0
while i < 5:
print(i)
i += 1
else:
print("Loop finished without break")
Output:
0
1
2
3
4
Loop finished without break
Infinite while Loop
An infinite while loop occurs when the loop’s condition never becomes False, meaning Python keeps executing the loop body endlessly.
For example:
i = 1
while i < 5:
print(i)
# Forgot to increment i
In this example, the value of i stays at 1, so the condition i < 5 is always True, causing the loop to run endlessly and create an infinite loop.
while Loop With Multiple Conditions
A while loop can have multiple conditions by using logical operators like and, or, and not.
The and Operator
The and operator requires all conditions to be True for the loop to continue. If any condition evaluates to False, the entire expression becomes False, and the loop ends.
For example:
password = "python123"
userinput = ""
attempts = 0
while userinput != password and attempts < 3:
userinput = input("Enter your password: ")
attempts += 1
if userinput == password:
print("Welcome aboard")
else:
print("Access denied. Too many attempts")
This code repeatedly asks the user for their password, allowing up to three attempts, and grants access only if the correct password is entered before the attempts run out.
The or Operator
The or operator allows the loop to keep running as long as at least one of the conditions is True.
For example:
age = 0
while age < 18 or age > 90:
age = int(input("Enter you age: "))
print("You are welcome")
This code repeatedly prompts the user to enter their age until they enter a value between 18 and 90, then displays a welcome message.
The not Operator
The not operator is used to reverse a condition, meaning the loop runs while the condition is False.
For example:
password_ok = False
while not password_ok:
password = input("Enter a password (at least 8 characters): ")
if len(password) >= 8:
password_ok = True
print("Password created successfully")
else:
print("Password too short")
This code repeatedly asks the user to create a password until they enter one that is at least 8 characters long, then confirms successful password creation.