Introduction: Python while Loop
The while loop is a fundamental control structure in Python that allows you to repeatedly execute a block of code as long as a specified condition is true. It provides flexibility and control over the flow of your program, especially when you don’t know in advance how many times the loop will run. In this article, we will delve into the Python while loop, explore its syntax and usage, and provide examples to demonstrate its versatility.
Syntax:
The syntax of the while loop in Python is as follows:
while condition:
# code block
The loop begins by evaluating the condition. If the condition is true, the code block associated with the while loop is executed. After executing the code block, the condition is evaluated again. If it remains true, the code block is executed again. This process continues until the condition becomes false, at which point the loop terminates, and the program proceeds to the next statement after the loop.
Example 1: Simple while Loop
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
In this example, we initialize the variable “count” to 1. The while loop executes the code block as long as “count” is less than or equal to 5. Inside the loop, the value of “count” is printed, and then it is incremented by 1 using the “count += 1” shorthand notation. The loop executes five times, printing the numbers 1 to 5.
Example 2: Interactive while Loop
password = ""
while password != "secret":
password = input("Enter the password: ")
print("Access granted!")
In this example, the while loop repeatedly prompts the user to enter a password until the input matches the string “secret”. Once the condition becomes false (i.e., the correct password is entered), the loop terminates, and the program proceeds to print “Access granted!”.
Infinite Loops:
When using while loops, it’s important to ensure that the condition eventually becomes false. If the condition always evaluates to true, the loop will run indefinitely, resulting in an infinite loop. It’s crucial to include a mechanism inside the loop to modify the condition, break the loop, or use control flow statements to prevent infinite loops.
Example: Infinite Loop with Break Statement
while True:
num = int(input("Enter a number (0 to exit): "))
if num == 0:
break
print("Square:", num**2)
In this example, the loop continues indefinitely until the user enters 0. Inside the loop, the program squares the entered number and prints the result. However, when the condition num == 0
is met, the break
statement is executed, causing the loop to break and exit.
Control Flow Statements:
Python provides additional control flow statements that can be used inside while loops to modify their behaviour.
- break Statement: The break statement allows you to exit the loop prematurely, even if the condition is still true. It is often used when a specific condition is met, and you want to stop the loop from further iterations.
Example:
count = 1
while True:
print(count)
count += 1
if count > 5:
break
Output:
1
2
3
4
5
In this example, the loop continues indefinitely, but when the value of “count” exceeds 5, the break statement is executed, terminating the loop.
- continue Statement: The continue statement allows you to skip the remaining code block for the current iteration and move to the next iteration of the loop.
Example:
count = 1
while count <= 5:
if count == 3:
count += 1
continue
print(count)
count += 1
Output:
1
2
4
5
In this example, when the value of “count” is 3, the continue statement is executed, skipping the print statement for that iteration. Consequently, the number 3 is not printed, and the loop proceeds to the next iteration.
The while loop is a fundamental construct in Python that allows you to repeatedly execute a block of code as long as a specified condition remains true. It provides flexibility and control over the flow of your program, making it suitable for situations where the number of iterations is not predetermined. In this article, we covered the syntax of the while loop, provided examples of its usage, addressed infinite loops, and discussed control flow statements such as break and continue. Understanding the while loop and its applications will greatly enhance your ability to write efficient and dynamic Python code.