Python While Loop Explained With Examples
The while loop repeatedly executes a block of statements as long as the condition evaluates to True. Flow control is a very important feature in any programming language. The real strength of programming isn’t just for the programs to start from the first line of code and simply execute every line, straight till the end. A program should be able to skip over a few instructions, return to them at some other point in time, repeat them, or simply choose one of several instructions to run. To achieve these tasks, Python provides various flow control statements, one of which is the while loop.
The topics discussed in this article are:
- Introduction to While Loop
- Break Statement
- Continue Statement
- While Loop with Optional Else
- More examples on While
Python Loops
Loops are important and one of the most basic concepts in any programming language. Looping basically means being able to repeat the execution of a certain portion of code more than once (known as iterations), based on loop parameters. Python offers two main looping constructs that serve different purposes: for and while statements. In this article, let’s focus on the while loop.
Best-suited Python courses for you
Learn Python with these high-rated online courses
The while loop
The python while statement is the simplest and the most basic iteration mechanism. It repeatedly executes a block of statements (usually indented) as long as the condition evaluates to True. When the test condition becomes False, the control moves to the statement that follows the while block. In case the test condition evaluates to False, to begin with, the body of the loop never runs and the while statement will be entirely skipped. Here’s a simple example that prints the numbers 1 to 10:
#Print numbers 1 to 10 using while loopcounter = 1while counter <= 10: print(counter) counter += 1
Ok! So, what’s happening here? As you can see the code is as simple as plain English. We first assigned the value 1 to the variable counter. The while loop starts by checking if the counter is less than equal to 10. If yes, then inside the while loop we printed the value of the counter and then incremented its value by 1. The control then again goes back to the beginning of the while loop, compares counter with 10, and then executes the while loop block if the condition is True. This goes on until the condition evaluates to False and when the condition is no longer satisfied, the loop ends. Python moves on to the next lines of code.
So, that’s how a while loop works! Simple right? While this is great, at times you would want to change the regular flow of a while loop. For example, skip an iteration (as many times as you want) or break out of the loop when you have acquired the results that match your requirement and such countless possible scenarios. To handle such situations, Python offers a break and continue statements.
The Break Statement
The break statement causes immediate exit of the loop. The code that follows the break is never executed and therefore you can also sometimes use it to avoid nesting in loops. Remember that break and continue only operate on a single level of the loop. In the case of nested loops, the break keyword-only terminates the loop where it is located. If a break is present in the innermost loop, it will only terminate the innermost for loop; any outer loop will continue to run.
Example: Here’s a simple program that will prompt the user to input a string and then convert it to upper case. The program should continue asking the user for the input until the value provided by the user is either ‘q’ or ‘Q’. If the user types ‘q’ or ‘Q’, the program stops executing.
#Cancel the execution of while loop with break statementwhile True: stuff = input("String to convert [type q or Q to quit]: ") if stuff == "q" or stuff == "Q": breakprint(stuff.upper())
As you can see, the program prompts the user to provide the input string from the keyboard via Python’s input() function and then prints the uppercase version of the string. The control breaks out of the while loop when the user enters either ‘q’ or ‘Q’.
The continue statement
Sometimes you might not want to break out of the loop but just want to skip ahead to the next iteration. In such a case, the continued statement comes to your rescue. It causes an immediate jump to the top of a loop. Just like break statements, you can use it to avoid statement nesting. Here’s a simple example:
Example: Write a program that will accept an integer input from the user, and prints the square of the number if the number is even, and if the number is odd, prints the message “num is odd. Enter an even number”. Also, the program should stop prompting for input if the user inputs the letter ‘q’ or ‘Q’.
#Skip the current iteration and go to next one with continue statementwhile True: input_value = input("Integer, please [q (or Q) to quit]: ") if input_value == 'q' or input_value == 'Q': # quit break number = int(input_value) if number % 2 == 0: # an even number print(number, "squared is", number*number) continue print(number, "is odd. Enter even number")
The while loop with optional else
One of the special features that the Python language offers is the ability to have else clauses after a while and for loops. If the execution of the while loop ends normally (when the testing condition evaluates to False), control passes to an optional else. In case the execution of the loop is interrupted by a break statement, the else clause will not be executed. You can use the optional else statement when you’ve coded a while loop to check for some condition and break as soon as it’s found.
Check Out the Best Online Courses
Example: Write a Python program that validates if given all the items of a given list are odd. If one of the items is even, the control should break out of the while loop and a relevant message has to be displayed.
#while loop with optional else clausetest_list = [1, 3, 5, 2, 7, 9, 13, 11]index = 0while index < len(test_list): num = test_list[index] if num % 2 == 0: print('Found even number', num, "at the position", index) break index += 1else: # executes when break not called print('No even number found! The list is odd')
More examples of while loop
Compute the average of numbers given by the user
Explore Free Online Courses with Certificates
Example 1: Write a program that computes an average. The program should keep asking the user to enter a number until the user types “done”. When the input is “done”, the program should then display the average of all the given numbers. Make use of control flow statements and break.
#Example1: Compute the average of numbers given by usersum = 0counter = 0while (True): input_value = input('Enter a number: ') if input_value == 'done' or input_value == "Done": break value = float(input_value) sum = sum + value #keeps track of the total sum counter = counter + 1 #keeps the count of number of inputs enteredaverage = sum / counterprint('Average:', average)
The above program clearly illustrates the functionality of the break statement that we discussed earlier. When the input provided by the user is either ‘Done’ or ‘done’, the control breaks out of the while loop and the statement after that is executed.
Use while loop to demonstrate the countdown and print a message when the count is 0
Example 2: Write a program that will demonstrate the countdown. So, the moment the count is 0, the program should print a message “Happy New Year ”.
#Example2: Demonstrating countdown using whiledef countdown(m): while m > 0: print(m) m = m - 1 print("Happy New Year!!")countdown(5)
Calculate binary representation of a given number
Example 3: Write a program that will calculate the binary representation of a given number.
#Example3: Calculate binary representation of given numberz = int(input("Please enter an integer: "))binary = [ ] #this will store the binary representation of the numberwhile z > 0: remainder = z % 2 #reminder after division by 2 binary.append(remainder) #keeps track of the reminders z //= 2 #dividing by twoprint("The wrong order", binary)binary = binary[::-1] #reversing the order of remaindersprint("The binary representation of", z ,"is", binary)
Check if the Given String is an Abecedarian Series
Abecedarian series refers to a sequence or list in which the elements appear in alphabetical order. Example: “ABCDEFGH” is an abecedarian series, while “BOB” is not.
#Example4: Check if a Given String is an Abecedarian Seriesdef is_abecedarian(string): i = 0 while i< len(string) - 1: if string[i + 1] < string[i]: return False i = i + 1 return True
print(is_abecedarian('BCDEFGH'))print(is_abecedarian('BOB'))
Print each character of a string in a new line using while loop
<span class="has-inline-color has-vivid-green-cyan-color">#Example5: Print each character of a string in new line using while loopstring1 = <span class="has-inline-color has-vivid-red-color">"I Love Python"<span class="has-inline-color has-vivid-cyan-blue-color">def <span class="has-inline-color has-luminous-vivid-amber-color">displaystring(<span class="has-inline-color has-vivid-cyan-blue-color">string): count = <span class="has-inline-color has-light-green-cyan-color">0 <span class="has-inline-color has-vivid-purple-color">while count < <span class="has-inline-color has-luminous-vivid-amber-color">len(string): <span class="has-inline-color has-luminous-vivid-amber-color">print(string[count]) count = count + <span class="has-inline-color has-light-green-cyan-color">1
displaystring(string1)
This is a pretty simple example. The loop iterates until the variable count is less than the length of the string. When the count equals the length of the string, the condition evaluates to False, and the body of the loop is not executed anymore.
FAQs
What are the three different types of loops in Python?
The three types of loops in Python are for loop, while loop, and nested loops. The for loop executes a group of statements a definite number of times. While loop repeats a statement or set of statements until a given condition is True. A nested loop is a loop inside the body of another outer loop.
What is the use of loops in Python?
Loops in Python help programmers execute a part of code repeatedly without writing the same line of code multiple times. Loops simplify complex problems into simple ones by repeating the same code over and over again.
What is the difference between Python for loop and Python while loop?
Python for loop repeats a block of code a definite or predetermined number of times. Python while loop executes a part of code as long as the condition is true.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio
Comments
(1)
M
10 months ago
Report Abuse
Reply to MD ARMAN