我已经开始在学校学习Python大约一个月了,我决定做一个测验。我已经添加了一个评分系统,所以如果你不正确地回答一个问题,它会告诉你你的分数。但是,这不起作用,它总会给你一个0的分数。另外,如果他们是一个问题而不是每一个问题都有一个方法,只有一个其他声明吗?谢谢:))
以下是代码示例(Python 3.2.3):
#QUIZ
print("Welcome to the quiz")
print("Please choose a difficulty:")
difficulty = input("A) Hard B)Easy")
if difficulty == "A":
score = 0
print("")
def question(score):
print("You chose the hard difficulty")
print("Where is the Great Victoria lake located?")
answer1 = input("A) Canada B)West Africa C)Australia D)North America")
if answer1 == "C":
print("Correct")
score = score+1
else:
print("you failed the quiz")
print("Score:",score)
quit()
def question2(score):
print("Who is most responsible for cracking the Enigma Code")
answer2 = input("A) Alan Turing B) Jeff Bezos C) George Boole D) Charles Babbage")
if answer2 == "A":
print("Correct")
score = score+1
else:
print("you failed the quiz")
print("Score:",score)
quit()
def diff_easy(difficulty):
if difficulty == "B":
score2 = 0
print("")
def question4(score2):
print("You chose the easy difficulty")
print("What is the capital of Australia?")
answer1 = input("A) Canberra B) Sydney C)Melbourne")
if answer1 == "A":
print("Correct")
score2 = score2+1
else:
print("you failed the quiz")
print("Score:",score2)
quit()
def question5(score2):
print("When was the Great Fire of London?")
answer2 = input("A) 1666 B) 1555 C)1605")
if answer2 == "A":
print("Correct")
score2 = score2+1
else:
print("you failed the quiz")
print("Score:",score2)
quit()
if difficulty == "A":
question(score)
question2(score)
if difficulty == "B":
diff_easy(difficulty)
question4(score2)
question5(score2)
答案 0 :(得分:3)
这是因为您在函数中看到的score
变量是您设置的score
变量的副本,按值传递 (我强烈建议您修改此主题)。你需要一种方法来传递状态。
现在很快就会发现对象(将来再也不会发生!),一个简单的解决方案就是使score
变量成为全局变量。只需替换
def question2(score):
与
def question2():
在所有的问题函数中添加global score
作为每个中的第一个语句,如下所示:
def question5():
global score
print("When was the Great Fire of London?")
answer2 = input("A) 1666 B) 1555 C)1605")
if answer2 == "A":
print("Correct")
score = score + 1
else:
print("you failed the quiz")
print("Score:", score)
quit()
将所有score2
的出现替换为score
,您就完成了。
当然,您可以针对所有问题使用单个if: else
分支。我不会给你完整的解决方案,所以你可以运动,但这里有一个提示:创建一个将带有三个参数的函数:
让我们调用此函数quiz
。现在您可以像这样使用它:
quiz("When was the Great Fire of London?", ["1666", "1555", "1605"], "1666")
quiz("What is the capital of Australia?", ["Canberra", "Sydney", "Melbourne"], "Canberra")
答案 1 :(得分:0)
像
这样的陈述 score2 = score2+1
代码中的无效,因为它们修改了局部变量。
对于另一个问题:您应该使用数据结构来存储问题和答案,以便您可以迭代它们而无需多次重复相同的代码。