[英]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.如果是,它将返回 Hello name 我希望你喜欢这个测验。 If not it gives an error message to say "this field cannot be left blank".如果不是,它会给出一条错误消息,提示“此字段不能留空”。
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.您在检查名称之前调用 return,因此 function 将在任何事情发生之前return
(退出)。
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: 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.另请注意, input
的默认类型是str
,因此您不需要强制转换它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.