我是python中的初学者,并且有一个类分配来创建类似于20-Questions游戏的脚本。到目前为止我开始这样做了:
# 20-Questions
#first question
q1= raw_input("Is it on the floor")
#continuation for first quesion "yes" answers
if 'yes' in q1:
print("It is on floor")
if 'yes' in q1:
q2a =raw_input("Is it smooth")
#continuation for first quesion "no" answers
if 'no' in q1:
print("It is not on the floor")
if 'no' in q1:
q2b=raw_input("Is it on the wall?")
#continuation for second quesion "yes yes" answers
if 'yes' in q2a:
print("It is smooth")
if 'yes' in q2a:
q3a=raw_input("Is it floor?")
#continuation for second quesion "yes no" answers
if 'no' in q2a:
print("It is not smooth")
if 'no' in q2a:
q3b=raw_input("Is it electronic?")
#continuation for second quesion "no yes" answers
if 'yes' in q2b:
print("It is on wall")
if 'yes' in q2b:
q3c=raw_input("Is it a poster?")
#continuation for second quesion "no no" answers
if 'no' in q2b:
print("It is not on wall")
if 'no' in q2b:
q3d=raw_input("Is it on the ceiling?")
#continuation for third question "yes yes yes"
if 'yes' in q3a:
print("It is floor, floor is good")
#continuation for third question "yes yes no"
if 'no' in q3a:
print("It must be desk,then...")
#continuation for third question "yes no yes"
if 'yes' in q3b:
print("It is computer, yes?, everthing electronic is computer")
#continuation for third question "yes no no"
if 'no' in q3b:
print("I dont know, lot of non-smooth and non-electronic things, not have enough time to code in")
#continuation for third question "no yes yes"
if 'yes' in q3c:
q3c=raw_input("Poster show great many things, so guess is good right?")
#continuation for third question "no yes no"
if 'no' in q3c:
q3c=raw_input("If poster not on wall, what is? Nail, cabniet, hole?; they not matter, poster matters")
#continuation for third question "no no yes"
if 'yes' in q3d:
q3d=raw_input("If on ceiling, then it must be light!")
#continuation for third question "no no no"
if 'no' in q3d:
q3d=raw_input("So it is not on celing, wall, or celing, where is it?; Your item must be invisible...")
else:
raw_input("you silly goose!, it is yes or no question!")
它给我一些未定义的变量的错误,但是我不能定义它们,因为我必须引导用户去预测它们的对象。
答案 0 :(得分:0)
您遇到麻烦的原因是当您只询问并设置与q2a对应的问题/变量时。变量q2b仍被检查为是或否答案。结果是你要求python检查q2b是真还是假,即使该人只被问到q2a的问题。因此变量没有设置,python会给你一个错误。
解决方案: 您的代码组织有点混乱。 重新思考组织方式,确保不检查尚未设置的变量。
答案 1 :(得分:-1)
创建一个函数,然后列出数组中的所有问题
def twenty_questions():
**questions_array** = ["is it on the floor?","is it smooth?", " is it on the wall?"]
# while loop for conditions
while usr_guess < 21: # max of 20 questions
# each guess is incremented by 1
guesses_taken = guesses_taken + 1
# print out question from the array & ask user questions
usr_guess = input(" > ",questions_array[0])
# yes or no to each question from the array
# repeat If-Else but change array value to fit question
if usr_guess ==("yes"):
print(questions_array[0]," = yes")
if usr_guess ==("no"):
print(questions_array[0]," = no")
else:
print(" yes or no questions")