Search code examples
python-3.xwhile-loopreturncode-structurefunction-definition

Best way to use returns to break from a loop


First of all, I'm not a native speaker, so please excuse me if there are grammatical errors. :) I'm a real greenhorn and just started to learn programming - i choose Python 3 as my first language. So please be lenient :) I already tried to find an answer by myself, but i wasn't successful. What is the better or more correct "style". Is there maybe a difference on runtime. Thank You!

Version 1:

def newUsername(db):
    isUser = True
    while isUser:
        username = input('Set an username:...')
        if not username:
            pass
        elif username in db:
            print("This user already exists!")
        else:
            isUser = False
    return username

Version 2:

def newUsername(db):
    while True:
        username = input('Set an username:...')
        if not username:
            pass
        elif username in db:
            print("This user already exists!")
        else:
            return username

Solution

  • The second version would be better.

    This is better since you are not using an additional variable & also reducing an expression where you assign that variable with a value.