在python 3.6中多次运行代码

在python 3.6中多次运行代码,python,Python,我试着让它只问“你想继续吗”3次,但它似乎不起作用,只是继续运行。我该如何解决这个问题?这是一个聊天响应程序,计算机问一个问题,用户回答 def choice(): prompts = [feeling, homesick, miss] random.choice(prompts)() for item in range(3): choice() 这是我为它编写的代码。但它不起作用 import random name = inpu

我试着让它只问“你想继续吗”3次,但它似乎不起作用,只是继续运行。我该如何解决这个问题?这是一个聊天响应程序,计算机问一个问题,用户回答

def choice():
        prompts = [feeling, homesick, miss]
        random.choice(prompts)()

for item in range(3):
    choice()
这是我为它编写的代码。但它不起作用

 import random
    
    name = input("What is your name? ")
    
    def restart():
        restart=input('do you want to continue? ')
        if restart=='yes':
            choice()
        else:
            print("ok, see you later!")
            exit()
            
    def feeling():
        response = input("How are you feeling right now {name}?".format(name=name))
        if response == "tired":
            tired = ['I wish I can make you feel better.','I hope school is not making you feel stressed.','You deserve the right to relax.']
            print(random.choice(tired))
            restart()
        else:
            print("Sorry, I don't understand what you mean by "+response+".")
            exit()
    
    def homesick():
        response = input("Do you miss your home? ")
        if response == "yes":
            yes=["Don't worry, you will be home soon......",'I am protecting your family and loved ones, trust me on this.',"Your kingdoms has been waiting for a long time, they'd forgiven your mistakes"]
            print(random.choice(yes))
            restart()
        else:
            print("Sorry, I don't understand what you mean by "+response+".")
            exit()
    
    def miss():
         response = input("Who do you miss?")
         if response == "my mom":
             print("Mom will be in town soon")
             restart()
         else:
            print("Sorry, I don't understand what you mean by "+response+".")
            exit()
    
    def choice():
        prompts = [feeling, homesick, miss]
        random.choice(prompts)()
    
    for item in range(3):
        choice()

达瓦克的评论是正确的。如果您想保持代码的其余部分不变,那么我只需修改
restart
函数,使其看起来像这样:

导入系统 def restart(): 如果输入('您想继续吗?')!='是的: sys.exit() 这样,如果用户的响应不是“是”,程序将退出;但是,如果它们的响应为“yes”,那么对
restart
的调用将不起任何作用,并且您的循环应该前进到下一个迭代

还有一点需要注意:不建议在程序中调用
exit
函数,因为它只是运行Python解释器时要使用的辅助函数。在程序中,您应该导入
sys
模块并调用
sys.exit
。来源:

每当你从感觉、想家或想念中执行restart()方法时,你总是执行choice()方法,所以它会再次询问你,直到你回答其他一些感觉“累了”的问题,“是”表示想家,或“我妈妈”表示想念。试着为提出这些问题的机制找出更好的流程。可能尝试添加一些计数器,这将在第三个问题“是否要继续”后终止脚本