Today, it’s time to review one more of Python’s legacy attributes. While Loops are some of the most valuable tools for programmers and a fundamental feature for any developer.
In this article, we plan to review every concept necessary to understand how While Loops work. We will also show you some code examples so you can have a clearer picture of what’s going on. While Loops are an easy concept, so you’ll have no trouble understanding them.
What are While Loops?
While Loops are a way of iterating through code. While loops are a specific kind of loop, some other types exist as well, with slightly different ideas behind them. Iteration means running a code statement a certain number of times or until a condition is met. Just keep that in mind for now.
When iteration occurs a specific number of times, it’s called definite iteration. Otherwise, we call it indefinite iteration.
While Loops fit into the indefinite iteration category. Why? Because until the final condition is reached, it will continue looping and running the code.
That’s all you need to know for now. Let’s see some basic code examples and review their syntax.
While Loops Syntax
To build a While Loop, we need a condition and a statement. The conditions are defined in the structure’s head and determine when a loop stops running. They are usually a boolean or an expression made with strings or numbers.
Once the condition is declared, we build a body where the statements go. This portion of the code runs until the condition is met.
The statement can contain any task we desire and can be a combination of functions, methods, and more. The last item of the body is usually the return. Have a look at this algorithm.
This is the basic outline of the syntax. Here, the “statement” section is indented with four white spaces and represents the looped code.
The “expression” tag represents a variable that gets checked as soon as the loop starts and continues to change until the condition it’s true. Let’s review a basic real-life example:
n = 10 while (n < 15): count += 1 print(n)
In the example above, we can appreciate the full functionality of the While Loop. First, we declare a variable that will serve as the condition in the loop’s head. Because the state is true, meaning that the number is not greater than 15, the loop runs one time.
Then, the statement adds 1 to our variable and prints the number. So, add 1 to 10, you get 11. Because 11 is still smaller than 15, the code loops once more, and so on, until the condition is met. In this case, when our variable number equals 15, the condition checks as false, and the loop stops running.
While Loops and Else Statements
We’ve seen how simple yet powerful a While Loop can be. It’s simple logic, but it that can lead to incredible results. Still, what about combining While Loops with other functions?
As is usual in Python, you can combine While Functions with most other native functions. For our purposes, we’ll use the “else” statement, another familiar resource for programmers.
The if-else statement usually works with one or more conditions, just like While Loops do. We’ll replace the “If” with the “While” this time. Therefore, when the first condition can’t be met, the else statement will get next in line.
Let’s make a simple program that utilizes the While Loop and the else statement, so you get the idea.
count = 0 while (count < 5): count += print("Hello World") else: print("Hello World from else statement") #Output #Hello World #Hello World #Hello World #Hello World #Hello World from else statement
In the example above, the count starts at 0 and increases continuously, printing a string with every loop. Then, when we reach 5, the While Loop stops, and the else statement prints the string we established before.
As you can see, like with most elemental tools, the possibilities really are endless. These simple combinations, which at their core represent simple logical statements, are the bread and butter of most applications.
One Line While Loops
As developers, we always seek opportunities to build cleaner and simpler code. There is a specific way of simplifying the syntax for While Loops that you should know about.
You can build a While Loop in a single line, declaring only the condition and the print section. Let’s see how it works:
n = 10 while n > 0: n -=; print(n)
Be aware that this syntax can lead to an infinite loop error because we can’t ever reach the necessary condition to stop it. In plain English, one-line While Loop (as written and defined in the above example) never ends. It loops forever.
When you find yourself in this situation, remember that you can terminate the program using a key combination on your keyboard. On Windows, Ctrl + C will get you out of trouble.
If this happens to you, don’t get discouraged. It’s a common error, and it’s actually an excellent way to understand the logic that underlies these functions.
However, there are some cases when we might want an infinite loop. Thus, depending on our intentions, infinite loops can be a feature, not a bug! For example, it’s a handy resource for building servers that must be online most of the time, as the server will keep functioning until you terminate the program. But let’s stay on track here.
While Loops With List
Let’s see how While Loops behave in combination with a list:
numbers = [1, 2, 3, 4, 5] while numbers: print(numbers.pop()) #Output #5 4 3 2 1
Here we’ve made a list containing numbers that will loop until no more items are left. While we won’t linger here, it’s pretty neat that you can combine While Loops with most native functions, and we want that to stay with you after you finish this article.
The condition section reads the list’s length, and we’ve established the last item as the first that gets printed. This is possible thanks to the pop() method.
The pop() method is a native function in Python that removes and returns the last item from a list. It works both with “for” loops and While Loops.
While Loops and Control Statements
Control statements are the ideal way to control the iteration of the While Loops. They allow us to modify how a loop works by terminating or interrupting the loop’s normal flow.
On the current Python version, we have two control statements:
First, the “continue” statement. It stops the current iteration and sends us to the beginning of the loop. The condition gets reevaluated, and a new repetition begins.
Here is an example of a While Loop with a Continue statement:
i = 0 a = 'Hello World' while i < len(a): if a[i] == 'o': i += 1 continue print(a[i]) i += 1 #Output: H e ll W r l d
Note that we call the len() function. It allows us to count the number of items and return this value. In this case, it returns the number of characters in the string.
There is also the “Break” statement. The break statement stops the loop from running entirely, like so:
i = 0 a = 'Hello World' while i < len(a): if a[i] == 'l': i += 1 break print(a[i]) i += 1 #Output: H e
Finally, we have the “pass” statement. It’s often used for empty loops with no statements, functions, or methods.
i = 0 a = 'Hello World' while i < len(a): i += 1 pass print(i) #Output: 11
All these control statements let us customize most of what happens inside a While Loop. You can see how this can be useful when working with large sets of data or when working with AIs.
What are the advantages of While Loops?
The main advantage of While Loops is that you can build whole applications upon them. Their functionality is so basic that you’ll always find yourself using them.
So far, we have seen how a While Loop works and how to combine it with other functions. The code examples were pretty simple, so let’s try to make something a bit more complex.
In Python, it’s possible to nest one or more statements within each other. Nesting works for if-else statements, While Loops, and other control structures.
a = ['Hello', 'World'] while len(a): print(a.pop(0)) b = ['Puthon', 'Rules'] while len(b): print('>', b.pop(0)) #Output: Hello Python Rules World Python Rules
In this example, we create a complex structure that evaluates conditions and prints each string. We also utilize the pop() function that we presented before.
This program is just another example of what is achievable with While Loops. They are mighty on their own, but everything goes to another level when you add other methods and functions to the mix.
Conclusion: While Loops In Python Explained
In this article, you learned how While Loops work, their syntax, and some use cases. With this knowledge, you should be able to dominate the concept of While Loops and implement them when needed.
We also looked at iteration, control statements, else statements, and infinite loops.
These are all features necessary to make a complex and useful application, using the repetition of code as the main foundational idea. For more information, we recommend checking out Python’s official documentation. Now, we leave you to try these things for yourself and see where they take you.