Introduction to Python While Loops
In Python, a while loop is used to repeatedly execute a block of code as long as a specified condition is true. It allows you to automate repetitive tasks and control the flow of your program based on certain conditions.
Syntax of a While Loop
The syntax of a while loop in Python is as follows:
while condition: # code to be executed
The condition is evaluated before each iteration. If the condition is true, the code block inside the loop is executed. Once the condition becomes false, the loop terminates and the program continues with the next line of code after the loop.
Examples of While Loops
Example 1: Counting from 1 to 5
Let’s start with a simple example that counts from 1 to 5 using a while loop:
count = 1 while count <= 5: print(count) count += 1
In this example, the variable count
is initialized to 1. The while loop continues as long as count
is less than or equal to 5. Inside the loop, the current value of count
is printed and then incremented by 1. The loop terminates when count
becomes 6.
The output of this code will be:
1 2 3 4 5
Example 2: Sum of Even Numbers
Now let’s look at an example that calculates the sum of even numbers from 1 to 10:
sum = 0 num = 1 while num <= 10: if num % 2 == 0: sum += num num += 1 print("Sum of even numbers:", sum)
In this example, the variable sum
is initialized to 0 and num
is initialized to 1. The while loop continues as long as num
is less than or equal to 10. Inside the loop, an if
statement checks if num
is even using the modulo operator (%
). If it is, num
is added to the sum
variable. Finally, num
is incremented by 1. The loop terminates when num
becomes 11.
The output of this code will be:
Sum of even numbers: 30
Example 3: User Input Validation
While loops are also useful for validating user input. Here’s an example that asks the user for a positive number:
number = -1 while number < 0: number = int(input("Enter a positive number: ")) print("You entered:", number)
In this example, the variable number
is initially set to -1. The while loop continues as long as number
is less than 0. Inside the loop, the user is prompted to enter a positive number using the input()
function. The input is converted to an integer using the int()
function. If the user enters a negative number, the loop continues. Once the user enters a positive number, the loop terminates and the program displays the entered number.
Conclusion
While loops are a fundamental part of programming in Python. They allow you to repeat a block of code based on a specific condition. With the help of examples, we have explored how while loops work and how they can be used in various scenarios. Remember to ensure that your loop condition eventually becomes false to avoid infinite loops. Practice using while loops to automate repetitive tasks and make your programs more efficient.