是否回答python中if语句的系统/游戏问题
我希望程序根据前一个问题的答案提出一个新问题。好几次。我可能完全做错了(我是个书呆子,想学) 如果我回答第一个问题“否”,第二个问题“是”,则会出现以下错误:是否回答python中if语句的系统/游戏问题,python,Python,我希望程序根据前一个问题的答案提出一个新问题。好几次。我可能完全做错了(我是个书呆子,想学) 如果我回答第一个问题“否”,第二个问题“是”,则会出现以下错误: 名称错误:未定义名称“Q2” 在我添加最后2个“如果”之前,它工作得很好。 谢谢你的回答,很抱歉拼写错误。我有诵读困难。你必须阅读。有一个非常好的东西叫做else。 我已经重写了你所做的: Q1 = input("stripes? answer yes or no: ") if Q1 == "yes": Q2 = input("h
名称错误:未定义名称“Q2”
在我添加最后2个“如果”之前,它工作得很好。
谢谢你的回答,很抱歉拼写错误。我有诵读困难。你必须阅读。有一个非常好的东西叫做else
。
我已经重写了你所做的:
Q1 = input("stripes? answer yes or no: ")
if Q1 == "yes":
Q2 = input("horizontal stripes? answer yes or no: ")
if Q2 == "yes":
Q4 = input("is ther 3 difrent colors or more? answer yes or no: ")
else:
Q5 = input("dose it have som sort of crest? answer yes or no : ")
else:
Q3 = input("is ther a cross? answer yes or no: ")
if Q3 == "yes":
Q6 = input("is ther 3 difrent colors or more? answer yes or no: ")
else:
Q7 = input("is ther a red bakround color? answer yes or no: ")
出现错误的原因是,如果为Q1输入输入“是”,则Q2尚未初始化。根据@pythad的答案使用条件语句 此外,您可以使用一个类来表示您的问题(可能是订单的一部分…),使其更具可伸缩性
什么不起作用?请花些时间阅读并初始化。Q1=Q2=Q3=Q4=Q5=Q6=Q7=“
Q2
如果Q1==“否”
,则尚未初始化。
Q1 = input("stripes? answer yes or no: ")
if Q1 == "yes":
Q2 = input("horizontal stripes? answer yes or no: ")
if Q2 == "yes":
Q4 = input("is ther 3 difrent colors or more? answer yes or no: ")
else:
Q5 = input("dose it have som sort of crest? answer yes or no : ")
else:
Q3 = input("is ther a cross? answer yes or no: ")
if Q3 == "yes":
Q6 = input("is ther 3 difrent colors or more? answer yes or no: ")
else:
Q7 = input("is ther a red bakround color? answer yes or no: ")
class OrderForm():
def __init__(self):
self.questions = {1:"stripes?",
2:"horizontal stripes?",
3:"is there a cross? ",
4:"is there 3 different colors or more?",
5:"does it have some sort of crest?",
6:"is there 3 different colors or more?",
7:"is there a red background color?"
}
self.responses = {k:'' for k in self.questions.keys()}
def ask(self, q):
try:
a = input(self.questions[q] + " answer yes or no: ")
a = a.lower().strip()
self.responses[q] = a if a in ['yes','no'] else ''
except:
# no response given
self.responses[q] = None
return self.responses[q]
def foo():
form = OrderForm()
if not form.ask(1):
print('Q1 is required...')
return
else:
with form.responses[1] as Q1:
if Q1 == 'yes':
form.ask(2)
if form.responses[2] == 'yes':
form.ask(4)
else:
form.ask(5)
elif Q1 == 'no':
form.ask(3)
if form.responses[3] == 'yes':
form.ask(6)
else:
form.ask(7)
print('\n'.join(['Q{} '.format(i) + form.questions[i] + '\t' + form.responses[i] for i in range(1, len(form.questions)+1)]))