Search code examples
pythonrepeatgoto

Repeating until done


So Ive got this code and I want to make it repeat itself until the user makes his username not start with a symbol or number.

  name=name.capitalize()
    print(name)
    surname= input("surname")
    surname=surname.capitalize()
    print(surname)
    password= input("password")
    username= input("username")
    first_char = username[0]
    if first_char.isalpha():
        print('done')
    else: print('username must start with a letter')

Solution

  • If you are using python 3.8, you can use the := operator for a nice way to write this:

    while not (username := input("username: "))[0].isalpha():
        print('username must start with a letter')
    # do stuff
    

    Otherwise your choices are going to be:

    (a) Repeat a line of code

    username = input("username: ")
    while not username[0].isalpha():
        print('username must start with a letter')
        username = input("username: ")
    # do stuff
    

    or (b) Use an infinite look with a break:

    while True:
        username = input("username: ")
        if username[0].isalpha():
            break
        print('username must start with a letter')
    # do stuff