-2

I am writing a script for prompting for a username. Username needs to be 3 or more and 10 or less characters in length. I want to refactor the code using while instead of repeating to prompt.

def hint_username(username):
    if len(username) < 3:
        print("Invalid Username, minimum of 3 characters")
        myUser = input("Please enter username: ")
        hint_username(myUser)
    elif len(username) >10:
        print("Invalid Username, maximum of 10 characters")
        myUser = input("Please enter username: ")
        hint_username(myUser)
    else:
        print("Valid Username")

myUser = input("Please enter username: ")
hint_username(myUser)
AMC
  • 2,642
  • 7
  • 13
  • 35
alvega2k
  • 3
  • 2

1 Answers1

0

You could do this as so with a while loop. I would not recommend recursively calling a function to validate user input.

def invalid_username(username):
    return not 3 <= len(username) <= 10


myUser = input("Please enter username: ")
while invalid_username(myUser):
    myUser = input(
        "Invalid username! Username must be 3 to 10 characters.\n"
        "Please enter username: "
    )

print("Valid Username")

Example code in Python tutor

Phillyclause89
  • 674
  • 4
  • 12