In the previous lesson, you learned how the Python for loop repeats a block of code while iterating through a sequence such as a string, list, tuple, dictionary, or a range of numbers. However, not every programming problem involves a fixed number of iterations.
Consider the following situations:
In these situations, you do not know in advance how many times the loop should execute. Instead, the loop should continue running as long as a particular condition remains True.
For these types of problems, Python provides the while loop.
The while loop repeatedly executes a block of code until its condition becomes False. Unlike the for loop, which is generally used to iterate through a sequence, the while loop is primarily used for condition-based repetition.
After completing this lesson, you will be able to:
while loop.while loop programs.while loop executes.for loop and the while loop.while loop to solve practical programming problems.while Loop?The Python while loop repeatedly executes a block of code as long as a specified condition evaluates to True.
Before every iteration, Python checks the condition. If the condition is true, the loop executes. If the condition becomes false, the loop stops immediately and the program continues with the next statement.
This makes the while loop ideal for situations where the number of iterations is unknown before the program starts.
while Loop?Many real-world applications cannot predict how many times an action must be repeated.
Examples include:
In these situations, using a for loop would not be appropriate because the exact number of iterations is unknown.
while Loopwhile condition:
statements
The syntax contains two main parts:
while – The keyword that starts the loop.condition – A Boolean expression that is checked before every iteration.statements – The code that repeats while the condition remains true.The statements inside the loop must be properly indented.
while Loop WorksThe execution of a while loop follows these steps:
True, the statements inside the loop execute.False.Unlike a for loop, the programmer is usually responsible for updating the variables that control the condition.
while Loop ProgramLet’s print the numbers from 1 to 5.
number = 1
while number <= 5:
print(number)
number += 1
Output
1
2
3
4
5
In this example:
number starts with the value 1.number <= 5 is checked before every iteration.number becomes 6, the condition becomes false and the loop ends.The following program prints even numbers from 2 to 10.
number = 2
while number <= 10:
print(number)
number += 2
Output
2
4
6
8
10
The loop continues until the condition is no longer true.
Consider the following program.
count = 1
while count <= 3:
print("Iteration:", count)
count += 1
print("Loop Finished")
Execution Steps
count.count <= 3 is evaluated.count is increased by one.count becomes 4.Output
Iteration: 1
Iteration: 2
Iteration: 3
Loop Finished
for Loop and the while Loop| for Loop | while Loop |
|---|---|
| Iterates through a sequence. | Repeats while a condition remains true. |
| Best when the number of iterations is known. | Best when the number of iterations is unknown. |
| Automatically moves to the next item. | Programmer must update the loop variable. |
| Less likely to become an infinite loop. | Can become an infinite loop if the condition never changes. |
while Loop?The while loop is appropriate when:
In this section, you learned what the Python while loop is and why it is useful for condition-based repetition. You explored its syntax, execution flow, and learned how it differs from the for loop. You also wrote beginner-friendly programs to print numbers and even numbers while understanding how the loop repeatedly checks its condition. In the next section, you will learn how to create counter-controlled and user-controlled while loops, use the break, continue, and else statements, build nested while loops, and avoid common beginner mistakes.
In the previous section, you learned the basic syntax of the Python while loop and how it repeatedly executes a block of code while a condition remains True. In this section, you will explore different types of while loops, learn how to control loop execution using break and continue, use the optional else clause, create nested while loops, and understand common mistakes made by beginners.
while LoopsA counter-controlled while loop uses a variable called a counter to control the number of iterations. The counter is updated during each iteration until the condition becomes false.
count = 1
while count <= 5:
print("Count =", count)
count += 1
Output
Count = 1
Count = 2
Count = 3
Count = 4
Count = 5
Here, the variable count increases after every iteration. Once its value becomes 6, the condition count <= 5 becomes false, and the loop ends.
while LoopsMany programs continue running until the user chooses to stop them. In such situations, a user-controlled while loop is the best choice.
choice = "yes"
while choice == "yes":
print("Program is running.")
choice = input("Continue? (yes/no): ")
Sample Output
Program is running.
Continue? (yes/no): yes
Program is running.
Continue? (yes/no): no
The loop continues until the user enters no.
An infinite loop is a loop whose condition never becomes false. As a result, it continues executing forever unless the program is stopped manually or interrupted.
while True:
print("Hello")
This program keeps printing Hello because the condition True never changes.
Infinite loops are useful in some situations, such as games, servers, and continuously running applications, but they must include a way to exit the loop.
break StatementThe break statement immediately terminates the loop, even if the loop condition is still true.
number = 1
while number <= 10:
if number == 6:
break
print(number)
number += 1
Output
1
2
3
4
5
When number becomes 6, the break statement immediately ends the loop.
continue StatementThe continue statement skips the remaining statements in the current iteration and moves directly to the next iteration.
number = 0
while number < 5:
number += 1
if number == 3:
continue
print(number)
Output
1
2
4
5
The number 3 is skipped because the continue statement transfers control to the next iteration.
else Clause with a while LoopPython allows an optional else block after a while loop. The else block executes only if the loop finishes normally without encountering a break statement.
count = 1
while count <= 3:
print(count)
count += 1
else:
print("Loop Completed Successfully")
Output
1
2
3
Loop Completed Successfully
If the loop ends using a break statement, the else block is skipped.
while LoopsA nested while loop is a while loop placed inside another while loop.
The inner loop executes completely for every iteration of the outer loop.
row = 1
while row <= 3:
column = 1
while column <= 2:
print(row, column)
column += 1
row += 1
Output
1 1
1 2
2 1
2 2
3 1
3 2
Nested while loops are commonly used for pattern printing and processing two-dimensional data.
Consider the following program.
count = 1
while count <= 4:
print("Iteration", count)
count += 1
print("Program Finished")
Execution Steps
count with the value 1.count <= 4 is checked.count increases by one.count becomes 5.Output
Iteration 1
Iteration 2
Iteration 3
Iteration 4
Program Finished
count = 1
while count <= 5:
print(count)
This creates an infinite loop because count never changes.
count = 1
while count <= 5:
print(count)
This results in an IndentationError.
Always verify that the loop condition eventually becomes false.
continue Without Updating the CounterIf the counter is not updated before continue, the loop may never terminate.
while count <= 5
print(count)
This produces a SyntaxError.
In this section, you learned how to create counter-controlled and user-controlled while loops, understood infinite loops, and explored the use of the break, continue, and else statements. You also created nested while loops, followed the execution flow step by step, and reviewed common beginner mistakes such as forgetting to update the loop variable, incorrect indentation, and writing conditions that never become false. In the next section, you will apply these concepts by building practical programs such as a number guessing game, password verification system, ATM menu, countdown timer, multiplication table generator, and sum of digits calculator.
The Python while loop is widely used in programs where the number of repetitions cannot be determined in advance. Many real-world applications such as login systems, ATM machines, games, and input validation continue running until a specific condition changes. The while loop is the ideal choice for these situations.
In this section, you will build several practical programs using the Python while loop. These examples will help you understand how condition-based repetition works in real programming scenarios.
while LoopThis program keeps asking the user to guess a number until the correct answer is entered.
secret_number = 7
guess = 0
while guess != secret_number:
guess = int(input("Guess the number: "))
print("Congratulations! You guessed correctly.")
Sample Output
Guess the number: 3
Guess the number: 5
Guess the number: 7
Congratulations! You guessed correctly.
The loop continues until the user enters the correct number.
Many applications repeatedly ask for a password until the correct password is entered.
password = ""
while password != "python123":
password = input("Enter Password: ")
print("Access Granted")
Sample Output
Enter Password: admin
Enter Password: hello
Enter Password: python123
Access Granted
The loop stops only after the correct password is entered.
An ATM menu usually remains active until the user selects the Exit option.
choice = 0
while choice != 4:
print("1. Balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
choice = int(input("Enter your choice: "))
print("Thank You for Using the ATM")
Sample Output
1. Balance
2. Deposit
3. Withdraw
4. Exit
Enter your choice: 4
Thank You for Using the ATM
The menu continues until the user chooses to exit.
A countdown timer decreases a value until it reaches zero.
count = 5
while count > 0:
print(count)
count -= 1
print("Time's Up!")
Output
5
4
3
2
1
Time's Up!
The loop stops automatically when the condition becomes false.
The following program generates the multiplication table of a number using a while loop.
number = 6
i = 1
while i <= 10:
print(number, "x", i, "=", number * i)
i += 1
Output
6 x 1 = 6
6 x 2 = 12
6 x 3 = 18
6 x 4 = 24
6 x 5 = 30
6 x 6 = 36
6 x 7 = 42
6 x 8 = 48
6 x 9 = 54
6 x 10 = 60
This program calculates the sum of all digits in a number.
number = 458
total = 0
while number > 0:
digit = number % 10
total += digit
number //= 10
print("Sum of Digits =", total)
Output
Sum of Digits = 17
The loop extracts one digit during each iteration until no digits remain.
The following program reverses the digits of an integer.
number = 1234
reverse = 0
while number > 0:
digit = number % 10
reverse = reverse * 10 + digit
number //= 10
print("Reversed Number:", reverse)
Output
Reversed Number: 4321
This program counts how many digits are present in an integer.
number = 987654
count = 0
while number > 0:
count += 1
number //= 10
print("Total Digits:", count)
Output
Total Digits: 6
Consider the following program.
count = 1
while count <= 3:
print("Current Value:", count)
count += 1
print("Loop Completed")
Execution Steps
count is initialized with the value 1.count <= 3.count is increased.Output
Current Value: 1
Current Value: 2
Current Value: 3
Loop Completed
while LoopsEnsure that the variable controlling the loop changes during each iteration.
Use conditions that are easy to understand and that eventually become false.
If you intentionally create an infinite loop, provide a way to exit it using break or another condition.
A loop should perform one logical task. Complex operations should be moved to functions whenever possible.
count = 1
attempt = 0
password = ""
Meaningful variable names improve code readability.
while loop when a for loop would be simpler.count = 1
while count <= 5:
print(count)
This program never updates count, so it creates an infinite loop.
count = 1
while count <= 5:
print(count)
count += 1
In this section, you applied the Python while loop to practical programming problems such as number guessing games, password verification systems, ATM menus, countdown timers, multiplication tables, digit calculations, reversing numbers, and counting digits. You also followed the execution flow step by step, explored best practices for writing reliable loops, and reviewed common beginner mistakes that can lead to infinite loops or incorrect program behavior. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on the Python break, continue, and pass Statements.
In this lesson, you learned how the Python while loop repeatedly executes a block of code as long as a specified condition remains True. Unlike the for loop, which is generally used when the number of iterations is known, the while loop is ideal for situations where the number of repetitions depends on a condition that changes during program execution.
You explored the syntax of the while loop, understood its execution flow, and learned how Python evaluates the loop condition before every iteration. You also practiced creating counter-controlled loops, user-controlled loops, nested while loops, and learned how to use the break, continue, and else statements to control loop execution.
Through practical examples such as password verification systems, ATM menus, countdown timers, multiplication tables, number guessing games, reversing numbers, and digit calculations, you learned how the while loop is used in real-world programming.
The Python while loop is an important control structure that helps developers create interactive programs, validation systems, games, and applications that continue running until a particular condition changes.
while loop executes repeatedly while a condition remains True.False.break statement immediately terminates a loop.continue statement skips the remaining statements of the current iteration.else block executes only if the loop finishes normally.while loops can be used for pattern generation and two-dimensional processing.while loop?A Python while loop repeatedly executes a block of code while a specified condition remains True.
while loop?Use a while loop when the number of iterations is unknown and repetition depends on a changing condition.
The loop body does not execute even once, and the program continues with the next statement.
An infinite loop is a loop whose condition never becomes False, causing it to run continuously.
break statement?The break statement immediately exits the loop regardless of the loop condition.
continue statement?The continue statement skips the remaining code in the current iteration and starts the next iteration.
else clause with a while loop?The else block executes after the loop finishes normally without encountering a break statement.
for loop and a while loop?A for loop is used for iterating through sequences, while a while loop is used for condition-based repetition.
while loop.while loop.while loop.while loop?while loop differ from a for loop?break statement?continue statement?else block execute in a while loop?while loop.Create a Python program that simulates a simple login authentication system using a while loop.
Your program should:
Enter Username: admin
Enter Password: test123
Invalid Username or Password. Try Again.
Enter Username: admin
Enter Password: python123
Login Successful
Welcome to the System!
Congratulations! You have successfully learned how to use the Python while loop for condition-based repetition. You now understand how to create loops that continue running until a condition changes, how to avoid infinite loops, and how to control loop execution using the break, continue, and else statements.
In the next lesson, you will learn the Python break, continue, and pass Statements. These control statements allow you to modify the normal execution of loops, skip iterations, terminate loops early, and create placeholder code while developing Python programs.