Python How do I add a loop to this so that it keeps asking user for their name if they leave the field blank. Then once name is entered it returns

Viewed 36

I want the system to check to make sure a name is entered. If it is it will return Hello name I hope you enjoy this quiz. If not it gives an error message to say "this field cannot be left blank".

This gets the user to enter their name

def hello():

    name=str(input("Please enter your name : "))
    
    if name == (""):
        print ("please enter your name this field cannot be blank")

    while name == (""):
        return
        name=str(input("Please enter your name : "))

    
    print("hello " + str(name))
    print ("I hope you enjoy this quiz")
    
hello() 
1 Answers

You are calling return before you check the name, so the function will return (exit) before anything happens.

Code:

def hello():

    name = input("Please enter your name : ")
    while name == (""):
        print("please enter your name this field cannot be blank")
        name = input("Please enter your name : ")

    print("hello", name)
    print("I hope you enjoy this quiz")
   
hello()

Output:

Please enter your name : 

please enter your name this field cannot be blank
Please enter your name : 
Ryan
hello Ryan
I hope you enjoy this quiz

Also note that the default type for input is str, so you do not need to cast it.

Related