繁体   English   中英

Python 如何在其中添加一个循环,以便在用户将该字段留空时不断询问他们的姓名。 然后一旦输入名称,它就会返回

[英]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

我希望系统检查以确保输入了名称。 如果是,它将返回 Hello 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() 

您在检查名称之前调用 return,因此 function 将在任何事情发生之前return (退出)。

代码:

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

另请注意, input的默认类型是str ,因此您不需要强制转换它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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