In this article we will learn how to keep programs running as long as users want them to. We will use Python while loop to keep programs running as long as certain conditions remain true. The while loop is used when you need your logic repeated until a certain condition is met, usually because you don't know how many times it will take. This could be because you are waiting for some condition to be met, like a timer expiring or a certain key press.
Python while loop syntax
The for
loop takes a collection of items and executes a block of code once for each item in the collection. On the other hand, the while
loop runs as long as, or while, a certain condition is true.
The general syntax of while loop would be:
while test: # Loop test
handle_true() # Loop body
else: # Optional else
handle_false() # Run if didn't exit loop with break
The while statement consists of a header line with a test expression, a body of one or more normally indented statements, and an optional else
part that is executed if control exits the loop without a break
statement being encountered.
Example-1: How to repeat python while loop a certain number of times
In this example we will write a code to repeat python while loop a certain pre-defined number of times. The general syntax to achieve this would be:
i = 0 while i < n: # do something here i += 1
It is important that in such condition we increment the count in each loop to avoid repeating the same loop. Here I have an example script where we want the while loop to be run 5 times. So we take a variable "count
" and assign the value as 1
. Next we put a condition with while loop to run the loop as long as the value of count
is less than or equal to 5. This was the loop will run exactly 5 times. It is important that we increment the value of count
after each iteration ends.
#!/usr/bin/env python3 count = 1 while count <= 5: print(count) count += 1
Output from this script:
Example-2: How to exit while loop in Python based on user input
We can use input()
function to collection some input from a user in Python programming language. Now this can be a repetitive task such as asking for password and unless both password attempt matches, the loop should continue to ask the user.
Here is our example script, where we ask for password two times to the user. If both password match then we exit the python while loop or else the code will continue to ask for password till eternity.
#!/usr/bin/env python3 while True: pwd1 = input("Enter new password: ") pwd2 = input("Retype your password: ") if pwd1 == pwd2: print('Perfect!!') break print("Both password don't match, try again..")
Output from this script:
Example-3: Using python while loop with a flag
In the previous example, we had the program perform certain tasks while a given condition was true. But what about more complicated programs in which many different events could cause the program to stop running?
We can write our programs so they run while the flag is set to True
and stop running when any of several events sets the value of the flag to False
. As a result, our overall while statement needs to check only one condition: whether or not the flag is currently True.
Let's add a flag to our previous example, we will call this flag as active
:
#!/usr/bin/env python3 # Set the flag as True initially active = True while active: pwd1 = input("Enter new password: ") pwd2 = input("Retype your password: ") if pwd1 == pwd2: print('Perfect!!') ## Instead of using break we set the flag active as False active = False ## Now we need an else condition as we are not breaking ## out of the while loop else: print("Both password don't match, try again..")
Output from this script:
Example-4: When to use continue
in a python while loop
Rather than breaking out of a loop entirely without executing the rest of its code, you can use the continue statement to return to the beginning of the loop based on the result of a conditional test.
For example, consider a loop that counts from 1 to 10 but prints only the odd numbers in that range:
#!/usr/bin/env python3 num = 0 # If num is less than 10 while num < 10: # increment num by 1 num += 1 ## Check for divided by 2 gives a remainder ## if remainder is zero, then it is an even number if num % 2 == 0: # If the loop enters here means even num found # so skip this num and continue with the loop continue # if condition was no match so print odd number print(num)
First we set num
to 0. Because it’s less than 10, Python enters the while loop. Once inside the loop, we increment the count by 1, so num
is 1. The if
statement then checks the modulo of num
and 2. If the modulo is 0 (which means num
is divisible by 2), the continue
statement tells Python to ignore the rest of the loop and return to the beginning. If the num is not divisible by 2, the rest of the loop is executed and Python prints the current number.
Output from this script:
Example-5: When to use break
in a python while loop
I have already used break
statement in one of my examples above. To exit a while loop immediately without running any remaining code in the loop, regardless of the results of any conditional test, use the break
statement. The break
statement directs the flow of your program; you can use it to control which lines of code are executed and which aren’t, so the program only executes code that you want it to, when you want it to.
For example here I have an infinite while loop where I ask user for some text input. Then the script will capitalize the first letter of the text unless user decides to quit by providing "q
" as an input.
#!/usr/bin/env python3 while True: text = input("String to capitalize [type q to quit]: ") if text == "q": break print(text.capitalize())
Here we read a line of input from the keyboard via Python’s input()
function and then print it with the first letter capitalized. We break out of the loop when a line containing only the letter q
is typed:
Example-6: How to use break with while and else condition in Python
If the while loop ended normally (no break call), control passes to an optional else. You use this when you’ve coded a while loop to check for something, and breaking as soon as it’s found. The else would be run if the while loop completed but the object was not found.
In this example script, we will look out for even numbers from a provided list of numbers.
#!/usr/bin/env python3 numbers = [1, 3, 5, 9] position = 0 while position < len(numbers): number = numbers[position] if number % 2 == 0: print('Found even number', number) break position += 1 # if break is not called then loop enters else condition else: print('No even number found')
Here also we are checking for a number divisible by 2 with 0 remainder. If no such number found then the loop enters else
condition of while loop. Output from this script:
~]# python3 example-5.py
No even number found
Example-7: How to use nested while loop in Python
Python allows you to nest loops. A nested loop is simply a loop that resides inside of another loop. There are lots of good reasons to use nested loops, from processing matrices to dealing with inputs that require multiple processing runs.
The syntax to use a nested while loop would be something like:
i = 0 while i < n: j = 0 while j < m: # do something in while loop for j j += 1 # do something in while loop for i i += 1
Suppose you are given the task of implementing a program that accepts a number from a user and then determines whether it is a prime number. The program also has to continue to accept values from the user until the user enters a zero.
To determine if a number is prime, you divide it by the values beginning at 2 and ending at the number. If none of those values results in a number without a remainder, the value is prime; if any one of the values does result in a number without a remainder, the number is not prime.
#!/usr/bin/env python3 while True: number = int(input("Enter a number: ")) if number == 0: break divisor = 2 isPrime = True while divisor < number: # break the loop if prime number if number % divisor == 0: isPrime = False break divisor += 1 if isPrime == True: print("The value ", number, " is prime") else: print("The value ", number, " is NOT prime") print("Done")
Output from this script:
~]# python3 example-6.py
Enter a number: 12
The value 12 is NOT prime
Enter a number: 14
The value 14 is NOT prime
Enter a number: 23
The value 23 is prime
Example-8: How to use python while loop with multiple conditions
In al the previous examples, we have defined a single condition with our python while loop. But it is also possible that there are multiple conditions to execute the loop. Here is one such example:
#!/usr/bin/env python3 i = 1 j = 10 while i < 5 and j > 1: i += 1 j -= 1 print(i, j)
Here we have added a condition to run the loop as long as the value of i
is less than 5 and value of j
is greater than 1. Inside the loop we are incrementing the value of i
by 1 and decrementing the value of j
in each iteration. Here is the output from this script:
Here are some more syntax to understand the usage of multiple conditions in python while loop:
while (a != b) and (a != c) and (a != d): # do something while (a != b) or (a != c) or (a != d): # do something while a not in { b, c, d }: # do something
Summary
In this article you learned how to use python while loop to make your programs run as long as your users want them to. You saw several ways to control the flow of a while loop by setting an active flag, using the break
statement, and using the continue
statement. You learned how to use a while loop in nested format with examples and syntax. It is recommended to use the while loop with caution when using with endless loop. It is important that you use a counter and always increment the counter at the end of iteration.
Further Readings
The while statement in Python
break and continue Statements, and else Clauses on Loops
Related Searches: python break while loop, python while loop example, python exit while loop, nested while loops python, how to end a while loop in python, python infinite while loop, python while loop multiple conditions, python while loop user input, python break out of while loop, python while loop syntax