Reputation: 23
I have a larger program which uses a lot of while
loops, and I have come across 2 ways in how to use them. Both produce the same result, but I am wondering which one is perhaps more efficient in terms of using resources etc.
def loop_1():
var = 0
while var != 1: # Until 'var' is 1
var = int(input("> "))
def loop_2():
while True: # Until 'break' is used
var = int(input("> "))
if var == 1:
break
Both loops stop if you enter 1, but does the break
syntax use more memory and resources than a regular while
loop in loop_1()
? I have a big program with a lot of while
loops which all use the break
syntax.
Upvotes: 2
Views: 303
Reputation: 22041
Either type of loop should be fine. Write what is easiest to read and understand. You might come back 10 years later and will want as little difficulty as possible to comprehend code you have not seen for the past 9 years. Anyone else who comes after you to read the code will be thankful as well if it is clear.
Upvotes: 2