根据条件

时间:2017-02-12 00:28:42

标签: python python-3.x

我正在制作一个简单的琐事游戏。我在下面提示用户并以交互方式显示问题。

我想添加一个"得分"特征。每当我尝试初始化"计数"在我Question类中的0或类似内容,并按value中存储的值递增,count保持为0.我在这里遇到了麻烦。理想情况下,我想在用户回答每个问题后打印得分。如果正确,则将self.value添加到count,否则减去。{/ p>

import random

class Question(object):
def __init__(self, question, answer, value):
    self.question = question
    self.answer = answer
    self.value = value



def ask(self):
    print (self.question + "?")
    count = 0
    response = input().strip()
    if response in self.answer:
        x = random.randint(0,3)
        print (positives[x])
        print ("Answer is" + " " + self.answer)


    else:
        y = random.randint(0,3)
        print (negatives[y])
        print ("Answer is" + " " + self.answer)



question_answer_value_tuples = [('This author made a University of Virginia law professor the    protagonist of his 2002 novel "The Summons"',
'(John) Grisham']
#there are a few hundred of these. This is an example that I read into Question. List of tuples I made from a jeopardy dataset. 

positives = ["Correct!", "Nice Job", "Smooth", "Smarty"]
negatives = ["Wrong!", "Think Again", "Incorrect", "So Sorry" ]


questions = []
for (q,a,v) in question_answer_value_tuples:
    questions.append(Question(q,a,v))

print ("Press any key for a new question, or 'quit' to quit. Enjoy!")
for question in questions:
    print ("Continue?")
    choice = input()
    if choice in ["quit", "no", "exit", "escape", "leave"]:
        break
    question.ask()

我想添加类似

的内容
count = 0
if response in self.answer:
    count += self.value
else:
    count -= self.value
print (count)

我认为我在使用本地/全局变量时遇到了麻烦。

1 个答案:

答案 0 :(得分:0)

每次调用“ask”时,都会将count重置为0.此外,count是一个局部变量,因为它只在ask()中定义。您需要将count作为类的成员并将其初始化为0.然后您可以像使用其他类变量一样使用它。请参阅下面的代码。

def __init__(self, question, answer, value):
 self.question = question
 self.answer = answer
 self.value = value
 self.count=0

def ask(self):
 print (self.question + "?")
 response = input().strip()
 if response in self.answer:
    x = random.randint(0,3)
    print (positives[x])
    print ("Answer is" + " " + self.answer)
    self.count += self.value


 ... etc

但是我对你在问题课程中包含你的分数的逻辑感到不满意 - 因为分数与众多问题有关,所以它需要在你班级或班级之外全局定义,所以当你打电话给你的方法时要求它应该返回答案是真还是假还是值,如此

 def ask(self):
  print (self.question + "?")
  count = 0
  response = input().strip()
  if response in self.answer:
    x = random.randint(0,3)
    print (positives[x])
    print ("Answer is" + " " + self.answer)
    return self.value
  else:
    y = random.randint(0,3)
    return 0

然后你做以下事情;

 score=0
 for question in questions:
  print ("Continue?")
  choice = input()
  if choice in ["quit", "no", "exit", "escape", "leave"]:
    break
  score+=question.ask()