While loops are next up, let’s look at what we have learned so far:
- Conditional Loops
- Uses If / Elif / Else logic
- For Loops
- Will loop over a set amount of times
While Loops
While loops will execute blocks of code as the condition you are evaluating remains true. A good real-world example of this would be driving to a destination. Sometimes you don’t know how many turns it will take to get from location A to location B. To visualize this:
driving = True
While driving:
if at_destination:
print('you are here!')
navigate = False
break
elif turn_right:
print('turning right')
continue
elif turn_left:
print('turning left')
continue
elif drive_straight:
print('going straight')
continue
What if you don’t know how often you want to loop over something? How can we write the logic in this instance? This is where while loops can help. While loops will continue to loop over as long as the condition you are evaluating remains true. For example, say you want to print Hello World 5 times. This is quickly done with a while loop:
counter = 0
while counter < 10:
print('Hello world!')
If you were to run the above code, you would be known as an indefinite loop, and the program would continue to run until the computer ran out of resources. We noted that we need a way to increment our counter so that the condition will be evaluated as false. This is an easy addition, which we have seen in a previous post:
counter = 0
while counter < 10:
print('Hello world!')
counter += 1
If we run this, Hello World will print ten times. To illustrate how it works, I printed the counter for each iteration.
Hello World! My counter is: 0
Hello World! My counter is: 1
Hello World! My counter is: 2
Hello World! My counter is: 3
Hello World! My counter is: 4
Hello World! My counter is: 5
Hello World! My counter is: 6
Hello World! My counter is: 7
Hello World! My counter is: 8
Hello World! My counter is: 9
Like with for loops, you can include conditionals into a while loop. An example would be if you are evaluating a bunch of numbers, say from 1 to 1000, and you want to raise to the power of two everything that is divisible by 20 and add that to a new list:
div_twenty = []
counter = 0
while counter < 1000:
if counter % 20 == 0:
div_twenty.append(counter)
counter += 1
If we ran the above, it would return:
div_twenty
[0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, 300, 320, 340, 360, 380, 400, 420, 440, 460, 480, 500, 520, 540, 560, 580, 600, 620, 640, 660, 680, 700, 720, 740, 760, 780, 800, 820, 840, 860, 880, 900, 920, 940, 960, 980]
We can also run a while loop while looking for a specific input type to break the loop.
while True:
name = input('What is your name: ')
if name == 'Mike':
break
else:
print(f'Hello {name}')
Running the above a few ways:
- Input James as your name
What is your name: James
Hello James
- Using Tammy as your name
What is your name: Timmy
Hello Timmy
- Finally, supplying Mike as your name.
What is your name: Mike
Break, Continue, and Pass
There is some new terminology that is introduced along with while loops.
- Break
- Will break you out of the current enclosing loop
- like from the example above
- Continue
- Go back into the loop and start with the next iteration
- Anything below the continue statement will not be processed
- Pass
- Does nothing.
- When designing functions and, if you are still planning them, you would use pass.
- Pass will go to the next line.
Continue Example:
We are running our while loop off of the length of a string. If we hit a counter value of 8, we will print the letter that correlates to the index of the counter, change c to 500, and continue. I will also print the new value of c after the continue statement shows it will not execute that code.
s = 'mynameisjimmy'
c = 0
while c < len(s):
if c == 8:
print(s[c])
c = 500
continue
print(f'Our counter is now: {c}')
c +=1
The above will print:
Our counter is now: 0
Our counter is now: 1
Our counter is now: 2
Our counter is now: 3
Our counter is now: 4
Our counter is now: 5
Our counter is now: 6
Our counter is now: 7
Pass Example:
lst = ['a','b','c','d','e']
cnt = 0
while cnt < len(lst):
if cnt == 3:
pass
print(lst[cnt:])
cnt+=1
This would return:
['a', 'b', 'c', 'd', 'e']
[
'b', 'c', 'd', 'e'
]['c', 'd', 'e']
[
'd', 'e'
]['e']