While Loops in Python [With Code Examples]

In Python, for loops work with collections of items. while loops on the other hand, work with conditions.

A for loop would continue to run till it gets to the last item in a collection. A while loop would continue to run till the condition evaluates to False.

while loop

An example of a while loop would be increasing the value of your phone’s battery indicator till it charges fully.

While the phone is still below 100%, the percentage value continues to increase and immediately it gets to 100%, it stops increasing.

Say your phone battery is on 94% and you just plugged it in. Let’s write the code

current_level = 94

while current_level <= 100:
    print(current_level)
    current_level += 1

print('Your battery is fully charged')

while loop

The first line of code initializes the condition to be tested for each iteration of the loop. This condition is being modified in the loop by adding 1 to it.

current_level += 1 is the same as current_level = current_level + 1

The condition is tested before executing the code in the loop again. When the condition evaluates to True, the code gets executed otherwise, the loop gets terminated.

Outside the loop, we included a message which will only get printed after the loop must have finished executing.

It is also possible to test for multiple conditions in while loops.

Infinite Loops

It is possible for a while loop to run forever. This happens when the condition is always True i.e. It never evaluates to False. Let’s change the condition of the previous code.

current_level = 94

while current_level >= 94:
    print(current_level)
    current_level += 1

print('Your battery is fully charged')

The condition will always be true because the battery percentage keeps increasing as specified in the loop (current_level += 1). It will also always be greater than 94 since that’s the current value from which we begin the increment.

The program will continue to run till your system runs out of memory. Double press the letter ‘i’ key on your keyboard to terminate the program.

One way to avoid this is to choose a condition that will at some time evaluate to False.

However, you might need an infinite loop in your program for certain reasons.

When you put your favorite song on repeat, it continues to play the song till you change it, stop it or quit your music player.

break Statement in while Loop

break statements are used to terminate while loops. When the loop encounters a break statement, it terminates the loop immediately.      

We can test for another condition in a loop and execute the break statement when this condition evaluates to True.

Let’s write a program to ask a user for their most favorite places in the world. We’ll append each response to a list.

Read: Python Lists

print('What places would you like to visit?')
fav_places =[]

while True:
    response = input('Please, enter a place: ')
    if response.lower() == 'quit':
        break
    fav_places.append(response)

print(fav_places)    

break statement

An infinite loop was introduced to keep asking for response from a user. while True is a popular convention for infinite loops. True is always True. This implies that the while condition will always be True

We used the input function to request for a response. This function takes a message as a parameter. input('Please, enter a place:  ') would print the message before a blinking cursor. Take note of how whitespace is used to separate the message from the cursor. This is just to improve readability.

The if statement is to check for the user’s response. If the user enters ‘quit’, the loop stops running and the remaining lines of the program get executed.

Take note of how Istanbul appears more than once in the list. We’ll take care of it shortly.

continue Statement in while Loop

continue statements are used to restart while loops. When the loop encounters a continue statement, it restarts the loop immediately.

By restarting the loop we mean, the remaining lines that come after the continue statement in the while loop are ignored. The loop goes back to the first line of code in the while loop.

Let’s modify the previous code. We’ll include an if statement to check if a response has not been supplied before by checking our list. If the response already exists, we’ll restart the loop and ask for another output. This way we ensure that multiple places don’t exist in our final list.

print('What places would you like to visit?')
fav_places =[]

while True:
    response = input('Please, enter a place: ')
    if response.lower() == 'quit':
        break
    if response.lower() in fav_places:
        continue
    fav_places.append(response.lower())

print(fav_places)    

continue statement

Multiple if statements were used to test for multiple conditions.

Summary

  • A while loop runs as long as the condition(s) evaluate(s) to True
  • An infinite loop occurs when the condition would never evaluate to False
  • A break statement is used to terminate the execution of a loop
  • A continue statement is used to restart a loop

No comments:

Powered by Blogger.