I have these 2 examples of while loops I read from the book 'Automate the Boring Stuff with Python", the book labeled this first one "An annoying while loop"
names = ''
while names != 'your name':
print('please type your name.')
names = input()
print('thank you')
The book showed this second example under the "Break statements" Section.
while True:
print("please type your name.")
namess=input()
if namess == 'your name':
break
print('Thank You')
Both codes respond the same way. My question is, when programming, should I always use the while loop along with the break statement, or are there instances in which the "annoying loop" is acceptable and should be used?
Thank you.
I was expecting a different behavior for the while loop along with the break statement.
I haven't read AtBS, but the real difference between the two loops is the first is a traditional while
loop, while the second is Python's "emulation" of a do
...while
loop; which is available in other languages.
The main difference between the two is in the first, the condition is checked when the loop body is entered. In the second, the condition is checked as the loop body exits.
You can look up the difference between while
and do
...while
loops to get a better idea, but in brief, the latter is useful when you need some setup before checking the condition even makes sense, and that setup is needed for every iteration of the loop anyway. That's the case here where names
outside of the loop needs to be available for the sake of the condition, but isn't needed otherwise.