首页 文章

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

提问于
浏览
0

我是编程的新手,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

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

    使用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()将在出错时重新运行程序 .

相关问题