简体   繁体   中英

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

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() 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM