提问人:RVN 提问时间:10/15/2022 最后编辑:DoodleVibRVN 更新时间:10/15/2022 访问量:62
测验打印错误猜测数的错误值
Quiz prints incorrect value for number of wrong guesses
问:
我希望以下代码打印程序用户在简单测验中输入的错误猜测的数量。
当前代码打印,并且没有其他值表示错误猜测的数量。是什么导致了这种行为?0
def new_game():
wrong_guess = 0
correct_guess = 0
question_num = 1
print("10-Question Automated Quiz")
print("Developed by: Wesly Farillon")
for key in questions:
print("-------------------------------------------------")
print("Question:", key)
print("\nChoices:")
for i in answers[question_num - 1]:
print(i)
guess = input("\nType your Answer here: ")
guess = guess.upper()
correct_guess += check_answer(questions.get(key), guess, wrong_guess)
question_num += 1
print("Score: ", correct_guess)
print("Wrong: ", wrong_guess)
def check_answer(answer, guess, wrong_guess):
if answer == guess:
return 1
else:
wrong_guess += 1
return 0
questions = {"Which method can be used to replace parts of a string?" : "A", "Which statement is used to stop a loop?" : "B",
"How do you start writing a while loop in Python?" : "A", "It refers to the spaces at the beginning of a code line" : "D"}
answers = [["A. replace()", "B. repl()", "C. switch()", "D. replacestring()"], ["A. stop", "B. break", "C. return", "D. exit"],
["A. while x < y:", "B. while (x < y)", "C. x < y while {", "D. while x < y {"], ["A. Syntax", "B. Comment", "C. Statement", "D. Indentation"]]
new_game()
答:
此代码不会准确打印错误猜测的数量,因为它不会递增它打印其值的变量。
感谢 Marcin 指出 Python 命名空间和作用域之间是有区别的:命名空间是“从名称到对象的映射”,通常是 Python 字典,许多东西都有与之关联的命名空间——例如模块和函数。作用域是“可直接访问命名空间的 Python 程序的文本区域”。可以想象,一个范围可以包含许多命名空间。[1]
此代码递增在函数范围内定义并位于命名空间中的调用的变量。调用 时,将为此变量分配一个初始值,该值等于函数作用域(位于命名空间中)中定义的变量的值。这些变量具有相同的名称,但它们存在于不同的命名空间中,并且不是同一个变量。wrong_guess
check_answer
check_answer
check_answer
wrong_guess
wrong_guess
new_game
new_game
wrong_guess
该代码打印函数范围内定义的变量的值,然后 boom - 你有你不希望的行为,其中打印的不准确猜测数量无法增加。wrong_guess
new_game
请注意,即使 in 在输入错误答案时递增,但每次运行代码时,该变量的值也会设置为 0(命名空间中另一个变量的值),原因与上述相同。该函数调用位于内部,并使用在局部作用域中找到的 (值 ) 为 提供参数。wrong_guess
check_answer
wrong_guess
wrong_guess
new_game
check_answer
new_game
wrong_answer
new_game
0
check_answer
参见 Real Python: Namespaces and Scope in Python [2]
评论
namespace
scooe
评论