在python 2.7中创建多个全局变量
我对Python相当陌生。我正在尝试创建一个自评分测验。到目前为止,我只有两个问题。我试图为这个人答对的数字和这个人答错的问题的数量分配一个全局变量。如果输入了所有正确的答案,程序就能正常工作;然而,任何不正确的答案都会被视为不正确,没有定义在python 2.7中创建多个全局变量,python,python-2.7,Python,Python 2.7,我对Python相当陌生。我正在尝试创建一个自评分测验。到目前为止,我只有两个问题。我试图为这个人答对的数字和这个人答错的问题的数量分配一个全局变量。如果输入了所有正确的答案,程序就能正常工作;然而,任何不正确的答案都会被视为不正确,没有定义 def test(): print "We are going to take a small quiz" print "Lets start with what your name." name = raw_input("What
def test():
print "We are going to take a small quiz"
print "Lets start with what your name."
name = raw_input("What is your name?")
correct = [0]
incorrect = [0]
def q1():
print "What organization did Hellboy work for?"
answer = raw_input("Type your answer.").lower()
if answer == "bprd" or answer == "b.p.r.d":
print "Your are correct."
correct[0] += 1
else:
print "That is wrong."
incorret[0] += 1
q1()
def q2():
print "What is the name of Captain America's sidekick?"
answer = raw_input("Your answer please.").lower()
if answer =="bucky barnes" or answer == "falcon":
print "Your are right"
correct[0] += 1
else:
print "Sorry that in incorrect"
incorrect[0] += 1
q2()
print "Good job %s, you got %r questions right and %r questions wrong" % (name, correct, incorrect)
raw_input()
test()
由于第一个问题中这一行的拼写错误,您将遇到未定义的错误:
incorret[0] += 1
纠正这一点,代码应该可以工作。如果将其设置为类,可能会更容易
class classTest():
def __init__():
print "We are going to take a small quiz"
print "Lets start with what your name."
self.name = raw_input("What is your name?")
self.correct = 0
self.incorrect = 0
def q1(self):
print "What organization did Hellboy work for?"
answer = raw_input("Type your answer.").lower()
if answer == "bprd" or answer == "b.p.r.d":
print "Your are correct."
self.correct += 1
else:
print "That is wrong."
self.incorrect += 1
def q2(self):
print "What is the name of Captain America's sidekick?"
answer = raw_input("Your answer please.").lower()
if answer =="bucky barnes" or answer == "falcon":
print "Your are right"
self.correct[0] += 1
else:
print "Sorry that in incorrect"
self.incorrect[0] += 1
def end(self):
print "Good job %s, you got %r questions right and %r questions wrong" % (self.name, self.correct, self.incorrect)
test = new classTest()
test.q1()
test.q2()
test.end()
指定您的问题,并让我们知道您尝试了什么。