我希望程序根据上一个问题的答案提出一个新问题。好几次。我可能做得完全错了(我是个笨蛋,想学习)
Q1 = input("stripes? answer yes or no: ")
if Q1 == "yes":
Q2 = input("horizontal stripes? answer yes or no: ")
if Q1 == "no":
Q3 = input("is there a cross? answer yes or no: ")
if Q2 == "yes":
Q4 = input("is there 3 difrent colors or more? answer yes or no: ")
if Q2 == "no":
Q5 = input("dose it have some sort of crest? answer yes or no : ")
if Q3 == "yes":
Q6 = input("is ther 3 different colors or more? answer yes or no: ")
if Q3 == "no":
Q7 = input(" is ther a red background color? answer yes or no: ")
如果我回答第一个问题"否"和第二个问题"是",则会出现以下错误:CCD_ 1。
它运行良好,直到我加上最后两个如果。谢谢你的回答,很抱歉拼写不好我有阅读障碍。
您必须阅读python中的条件语句。有一个非常好的东西叫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输入输入"yes",则会发生错误,因为Q2尚未初始化。根据@pythad的回答使用条件语句。
此外,您可以使用一个类来表示您的问题(可能是订单形式的一部分…),使其更具可扩展性
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)]))