[英]Restarting my program based on user input on Python?
我是编程新手,老兄。 我希望我的程序根据用户输入重新启动到顶部。 如果用户输入2个名称,它将继续进行。 如果他们输入1个名称或两个以上的名称,则应重新启动程序,但我不确定如何执行此操作。
def main():
print("Hello, please type a name.")
first_name, last_name = str(input("")).split()
while input != first_name + last_name:
print("Please enter your first name and last name.")
main()
您应该使用while循环并在分配前检查拆分的长度:
def main():
while True:
inp = input("Please enter your first name and last name.")
spl = inp.split()
if len(spl) == 2: # if len is 2, we have two names
first_name, last_name = spl
return first_name, last_name # return or break and then do whatever with the first and last name
好吧,您的程序从一开始就不起作用,因此,为了简单地解析名字和姓氏,我建议:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
如果您在没有良好的'ol ctrl + c的情况下运行循环,那么while循环将破坏您的生命。 因此,我建议:
def main():
print “type your first & last name”
try:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
if f and l:
return f + ‘ ‘+ l
except:
main()
例外:main()将在出现错误时为您重新运行该程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.