Member-only story

Python: While Loop Basics

Jesse L
3 min readDec 9, 2021

--

Hi everyone, welcome back. While loops are used in Python to continue to iterate over a segment of code as long as a specific condition is met. This type of capability can be useful for many cases. In this article, we will go over how a while loop works. Let’s get into it.

While Loop with Numbers

As said previously, a while loop will continue to iterate through a segment of code as long as a condition has been met. Inside the loop we will need some sort of control over the condition, a way to change it, otherwise we will be stuck in the loop forever, or an infinite loop. Let’s see how a while loop is done:

x = 1
while x < 5:
print(x)
x += 1
Output:
1
2
3
4

Our condition is set that our loop will iterate as long as x is less than 5. We first start with x equal to 1, and within the loop we are incrementing x by 1. As we can see in our output, we only iterated 4 times and exited the loop as soon as x was set to 5.

While Loop with List

Let’s see how a while loop can work with a list:

list = [1, 2, 3]
while list:
print(list.pop())
Output:
1
2
3

In this example, we have created a list with 3 values. How this while loop works is that if…

--

--

Jesse L
Jesse L

Written by Jesse L

Hi, I'm a passionate technology enthusiast and lifelong learner. Beyond my technical pursuits, I'm also passionate about sharing my enthusiasm with others.

No responses yet