A while loop in Python is a control flow statement that allows you to repeat a set of instructions as long as a specified condition is true.
It is a type of iteration statement that is useful when you don’t know in advance how many times you need to repeat a certain task.
While Loop Syntax
The syntax for while loop in Python is as follows:
while <condition>:
statement
else:
statement
In a while
loop, the condition is tested at the beginning of each iteration, and if it is true, the loop body is executed.
Once the loop body has finished executing, the condition is checked again, and the loop continues until the condition becomes false. If the condition is false from the beginning, the loop is skipped entirely.
The else part of while statement is optional, but when provided, it always gets executed when the loop ends.
While Loop Example
Here’s a simple example of a while
loop that prints the numbers 0 to 4:
i = 0
while i < 5:
print(i)
i += 1
Output:
0 1 2 3 4
In the above example, the loop body will execute as long as i is less than 5. Once the value of i exceed 5, the execution of the loop stops.
One common use case for while
loops is when you’re reading input from a user or a file and you don’t know in advance how many items there will be.
For example, you could use a while
loop to read in a list of integers from the user until they enter a negative number:
numbers = []
while True:
n = int(input("Enter a number (negative to quit): "))
if n < 0:
break
numbers.append(n)
print(numbers)
Here, the loop condition is True
, which means that the loop will run indefinitely until it is explicitly terminated using the break
statement.
Inside the loop, we read in a number from the user using input
, convert it to an integer using int
, and then append it to a list called numbers
.
If the user enters a negative number, we exit the loop using break
. Once the loop has terminated, we print out the final list of numbers.
Example with else
Sometimes, irrespective of the condition of the while loop, you may want to execute some lines of code at the end of the while loop. For this you should use else
condition, like the following:
#using while and else
x=0
while x<10:
print("result",x)
x+=1
else:
print("thanks")
Output:
result: 0
result: 1
result: 2
result: 3
result: 4
result: 5
result: 6
result: 7
result: 8
result: 9
thanks
As you can see, in the end the program outputs ‘thanks’ as intended.
Overall, while
loop in python is useful when you need to repeat a certain task for a number of times or until a certain condition is met. They’re a fundamental building block of programming and are used extensively in many different types of applications.