2

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.

1
  • 5
    Whether you use while x: or while True: ... if ! x: break Should not make much of a difference in terms of performance. The problem probably lies elsewhere. Commented Mar 10, 2017 at 14:46

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks, yeah I was using the 'break' syntax and I just found it so much easier to comprehend when looking back over it, again I was just curious to whether or not using 'break' to break out of a loop impacted performance. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.