当给出错误的输入和决策树时返回并重试

Go back and retry when given wrong input & decision tree

所以我对编码和使用 python 是全新的,所以我一直在四处查看教程,现在我试图通过稍微弄乱来弄湿我的脚。我在 ipython 中做所有事情,同时在 mac 上的应用程序括号中制作脚本...不知道这是否会改变任何东西。只是一些额外的信息。

所以,我正在尝试将决定输入到如果没有用 "yes" 或 "no" 回答的地方,那么代码将响应 "please answer with 'yes or 'no'" 然后询问他们一遍又一遍,直到输入 "yes" 或 "no"。我不希望脚本在输入 "yes" 或 "no" 以外的内容时结束。

print ("Welcome!")
myName = input("What is your name, friend?: ")
dec = input("So, " + (myName) + ", would you like to hear a story? (yes or no): ")
def decision():
    if (dec == "yes"):
        print("Wonderful")
    elif (dec == "no"):
        print("Maybe another time then?")
    else:
        print("Please answer with 'yes' or 'no'")
decision()

此外,我将如何从中制作决策树?因此,如果有人回答 "yes",那么他们将被问到另一个问题,并记下故事中的不同路线,而不是如果他们回答了 "no"(或 yes/no 以外的其他问题)。

谢谢!

所以 if 语句将成为你最好的朋友!我推荐的另一件事是 while 循环!所以每次你要求用户输入是或否时,都在一个 while 循环中完成!

userAnswer =input("Yes or no??")
while (userAnswer != yes and userAnswer != no):
    userAnswer = input("Yes or no???")

基本上一直问他们,直到他们说是或否。根据你的决策树,你可以做很多嵌套的 if 语句,或者你可以编写很多在用户回答 yes/no 后调用的方法。希望对您有所帮助!

您可以整理(并允许输入任何情况)DROP TABLE 先生这样回答:

userAnswer =input("Yes or no??")
while userAnswer.lower() in ('yes', 'no'):
    userAnswer = input("Yes or no???")