根据Python上的用户输入重新启动我的程序?

时间:2014-10-18 23:50:10

标签: python

我是编程的新手,fyi。我希望我的程序根据用户输入的内容重新启动回到顶端。如果用户输入2个名称,它将继续。如果他们输入1个名字或2个以上的名字,它应该重启程序,但我不知道该怎么做。

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

2 个答案:

答案 0 :(得分:1)

你应该使用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

答案 1 :(得分:0)

使用try/except

嗯,你的程序对我来说不起作用,所以简单地解析名字和姓氏,我建议:

f, l = [str(x) for x in raw_input("enter first and last name: ").split()]

另外,你的while循环只会像你在没有良好的'ol ctrl + c'的情况下运行它一样打破你的生活。所以,我建议:

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()会在出错时为你重新运行程序。

相关问题