超级困惑为什么我的division()
方法不能运行,其他一切都很好。我知道这有多愚蠢,但我非常困惑。我还包括了其他方法,但由于不需要,iv删除了它们,我的其他方法可以使用相同的精确代码,但除法无法运行
def TudorSelect():
TaskSelect = input(
"Please select one of the following tasks to practice; Addition, Subtraction, Multiplication, Divison: "
)
global total
global difficulty
difficulty = int(
input("Please select the max value range of your values: 0 - "))
print(chr(13))
total = int(input("Total practice questions for this task: "))
if TaskSelect == "Addition":
addition()
elif TaskSelect == "Subtraction":
subtraction()
elif TaskSelect == "Multiplication":
multiplication()
elif TaskSelect == "Divison":
division()
def division():
for num in range(total):
global correcttotal
randvalue1 = random.randint(1, difficulty)
randvalue2 = random.randint(1, difficulty)
correctvalue = (randvalue1 / randvalue2)
print(str(randvalue1), " / ", str(randvalue2))
uservalue = input()
if uservalue == str(correctvalue):
print("Correct")
correcttotal = correcttotal + 1
else:
print("False")
print("Correct answer is ", str(correctvalue))
CorrectRate = ((correcttotal) / (total)) * 100
print("Your total mark is ", str(CorrectRate), "%")
TudorSelect()
我认为您对使用
global
有一个误解,global
用于修改局部范围中的全局变量,因此尝试使correcttotal
全局是没有用的,correcttotal
只在函数中声明因此,要解决此问题,需要从循环中删除
global
关键字,并在循环外定义累加器correcttotal
,它需要在循环外处于活动状态才能正确累加:现在,当你像这样运行它
它工作正常,而且你的答案检查非常严格,我不是一台超级计算机,至少在答案的浮点部分达到那样的准确度,我认为你需要先把答案四舍五入,然后与学生的答案进行比较
最后,我真的不建议使用
global
,为什么不把它作为一个参数传递给你的函数呢?相反,它会更可读,更容易跟踪相关问题 更多 >
编程相关推荐