我试着让它只问“你想继续”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()
答案 0 :(得分:1)
达尔瓦克的评论是正确的。如果你想保持其余的代码相同,那么我只想修改restart
函数看起来像这样:
import sys
def restart():
if input('do you want to continue? ') != 'yes':
sys.exit()
这样,如果用户使用“是”之外的任何内容进行响应,该程序将退出;但是,如果他们回答“是”,那么对restart
的调用就什么都不做了,你的循环应该进入下一次迭代。
还有一点需要注意:不建议在程序中调用exit
函数,因为它只是在您运行Python解释器时使用的辅助函数。在程序中,您应导入sys
模块并致电sys.exit
。资料来源:Difference between exit() and sys.exit() in Python