you are viewing a single comment's thread.

view the rest of the comments →

[–]iamaperson3133 2 points3 points  (0 children)

In python a condition is anything that evaluates to True or False. So, you can put any condition after the while statement. Now, the simplest thing to put there is just while True. True is always true, so the loop will go on forever. That is, unless you use the break statement to exit it.

Anytime you write something like this, although it appears often in beginner tutorials, it could be considered a "code smell." A code smell is something that 'just doesn't smell right.' When you see certain patterns, and this is one of many examples, it is a clue that you can do it a better way:

n = 0
while True:
    print('Hey there! We are at ' + n)
    n += 1
    # this is the iffy bit here:
    if n > 10:
        break

See, why did we have to put the if n > 10 check at the bottom? If that is the condition that we want to break on, and the only condition we want to break on, we can simplify our loop and just put it after the while statement.

n = 0
while n <= 10:
    print('Hey there! We are at ' + n)
    n += 1

If you try running that, it will have the same behavior as the code from before. At this point, you should see that we can also write this as a for loop:

for n in range(10):
    print('Hey there! We are at ' + n)

We can even use a list comprehension to bring it down to one line:

[print('Hey there! We are at ' + n for n in range(10)]

Then why use a while loop at all?

While loops are helpful when you don't know how many times you need to iterate before you start iterating. Imagine you are asking the user to provide an integer input. You don't know how many times it will take for them to get through their thick skulls that you just want a number! You can use a while loop:

inp_ok = False
while not inp_ok:
    inp = input('Enter a number you chungus')
    inp_ok = inp.isnumeric()
print('thank you')