In this tutorial, you'll learn how to use the while loop in Python. The while loop is a control flow statement that allows code to be executed repeatedly based on a given Boolean condition. It's particularly useful when you don't know beforehand how many times the loop should run.
The while loop is one of the fundamental constructs in programming, allowing for repeated execution of a block of code as long as a specified condition remains true. Unlike the for loop, which iterates over a sequence, the while loop continues to execute as long as its condition evaluates to True.
The basic syntax of a while loop in Python is:
1while condition:2# code block to be executed
True, the loop body executes; if it's False, the loop terminates.Example 1: Basic While Loop
Let's create a simple program that counts down from 5 to 1 using a while loop.
1counter = 52while counter > 0:3print(counter)4counter -= 1
5 4 3 2 1
In this example, the loop continues to execute as long as counter is greater than 0. After each iteration, the value of counter is decremented by 1.
The while loop is ideal for situations where you need to perform an action repeatedly until a certain condition changes. This makes it suitable for tasks like reading input from the user or processing data until a specific result is achieved.
Example 2: User Input Validation
Suppose we want to ask the user to enter a positive integer and keep prompting them until they provide valid input.
1while True:2try:3number = int(input("Enter a positive integer: "))4if number > 0:5print(f"You entered {number}.")6break7else:8print("Please enter a positive integer.")9except ValueError:10print("Invalid input. Please enter a valid integer.")
Enter a positive integer: -5 Please enter a positive integer. Enter a positive integer: abc Invalid input. Please enter a valid integer. Enter a positive integer: 7 You entered 7.
In this example, the loop continues indefinitely until the user enters a positive integer. The break statement is used to exit the loop when valid input is received.
An infinite loop occurs when the condition of a while loop always evaluates to True, causing the loop to run indefinitely. While intentional infinite loops are sometimes useful (e.g., in server applications), they can also be accidental and lead to program crashes if not properly managed.
Example 3: Intentional Infinite Loop
Here's an example of an intentional infinite loop that simulates a simple server:
1while True:2request = input("Server received a request. Process? (yes/no): ")3if request.lower() == 'no':4print("Shutting down the server.")5break6else:7print("Processing request...")
Server received a request. Process? (yes/no): yes Processing request... Server received a request. Process? (yes/no): no Shutting down the server.
In this example, the loop runs indefinitely until the user types 'no', at which point it breaks out of the loop.
Tip: To stop an infinite loop during execution, you can use keyboard interrupts (Ctrl+C in most environments).
The while loop can also include an optional else clause. The else block is executed when the loop condition becomes false, but not if the loop was terminated with a break statement.
Example 4: Using while...else
Let's modify the countdown example to use a while...else construct:
1counter = 52while counter > 0:3print(counter)4counter -= 15else:6print("Countdown finished!")
5 4 3 2 1 Countdown finished!
In this example, the else block is executed after the loop completes normally. If the loop had been terminated with a break, the else block would not execute.
Using counters is a common technique in loops to keep track of iterations or conditions. This can be useful for tasks like limiting the number of attempts or processing a fixed number of items.
Example 5: Using Counters
Suppose we want to read a file line by line, but only process up to 10 lines:
1with open('example.txt', 'r') as file:2count = 03while count < 10 and (line := file.readline()):4print(line.strip())5count += 16else:7if line == '':8print("Reached the end of the file.")9else:10print("Processed 10 lines.")
Line 1 Line 2 ... Line 9 Line 10 Processed 10 lines.
In this example, the loop processes up to 10 lines from a file. The else block is executed if the loop completes normally (i.e., it processed 10 lines), or if it reaches the end of the file.
Let's create a complete program that simulates a simple guessing game. The computer randomly selects a number between 1 and 10, and the user has to guess it. The game continues until the user guesses correctly.
1import random23def main():4secret_number = random.randint(1, 10)5attempts = 06guessed_correctly = False78print("Welcome to the Guessing Game!")9while not guessed_correctly:10try:11guess = int(input("Guess a number between 1 and 10: "))12attempts += 113if guess < secret_number:14print("Too low. Try again.")15elif guess > secret_number:16print("Too high. Try again.")17else:18guessed_correctly = True19except ValueError:20print("Invalid input. Please enter a valid integer.")2122print(f"Congratulations! You guessed the number in {attempts} attempts.")2324if __name__ == "__main__":25main()
Welcome to the Guessing Game! Guess a number between 1 and 10: 5 Too low. Try again. Guess a number between 1 and 10: 8 Too high. Try again. Guess a number between 1 and 10: 7 Congratulations! You guessed the number in 3 attempts.
In this example, the while loop continues until the user guesses the correct number. The program keeps track of the number of attempts using a counter.
| Concept | Description |
|---|---|
| While Loop Syntax | Executes code repeatedly while a condition is true. |
| Condition-Based | Suitable for tasks where the loop runs until a specific condition changes. |
| Infinite Loops | Occur when the loop condition always evaluates to True. |
| While...Else | The else block executes if the loop completes normally, not with a break. |
| Loop Control | Using counters helps manage iterations and conditions effectively. |
In the next tutorial, you'll learn about controlling loops using break, continue, and pass statements. These statements provide more control over the flow of execution within loops, allowing for more complex logic and efficient code.
Stay tuned!