Python While Loop

The while loop in Python allows you to repeatedly execute a block of code as long as a certain condition is true. Here’s the basic syntax:

while condition:
    code block

The code block will be executed repeatedly until the condition evaluates to False. It’s important to include a way to change the value of the condition within the code block, or else the loop will run indefinitely and you’ll have an infinite loop on your hands! Here’s an example of a simple while loop that counts from 1 to 10:

count = 1
while count <= 10:
    print(count)
    count += 1

This while loop will print the numbers 1 through 10, because the value of count is incremented by 1 at the end of each iteration.

You can also use the break and continue statements within a while loop. The break statement will exit the loop entirely, while the continue statement will skip the rest of the current iteration and move on to the next one. Here’s an example that uses both break and continue:

count = 0
while True:  # this creates an infinite loop
    count += 1
    if count > 10:
        break  # exit the loop when count is greater than 10
    if count % 2 == 0:  # if count is even
        continue  # skip the rest of the current iteration
    print(count)

This while loop will print the numbers 1, 3, 5, 7, and 9, because the continue statement skips the rest of the current iteration when count is even. The break statement then exits the loop when count is greater than 10.

It’s also possible to use an else clause with a while loop. The else clause will be executed when the while loop terminates normally (i.e., when the condition becomes False), but it will not be executed if the loop is terminated by a break statement. Here’s an example that uses an else clause:

count = 0
while count < 5:
    count += 1
else:
    print("Count is no longer less than 5")

This while loop will print “Count is no longer less than 5” because the loop terminates normally when count becomes equal to 5.

You can also nest while loops within each other. This can be useful for iterating over a multidimensional data structure, such as a list of lists. Here’s an example of a nested while loop:

data = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
i = 0
while i < len(data):
    j = 0
    while j < len(data[i]):
        print(data[i][j])
        j += 1
    i += 1

This nested while loop will print the numbers 1 through 9, because it iterates over each element in the data list of lists.

It’s important to use caution when using while loops, because it’s easy to create an infinite loop if the condition is not written correctly.

Was this helpful?
[0]