我每次运行该函数时都试图增加计数,似乎每次运行该函数时都会重置count。我认为if语句中的计数可能与作为条件传递的计数不同。感谢
def check_solution(user_solution, solution, count):
if user_solution == solution:
count =+1
print(count)
return count
else:
print("Incorrect")
这是我用来调用函数
的代码if index == 1:
solution = num_1 + num_2
num_1 = str(num_1)
num_2 = str(num_2)
problem = (num_1 + "+" + num_2)
user_solution = get_user_solution(problem)
check_solution(user_solution, solution, count)
return count
答案 0 :(得分:2)
声明应该是count += 1
而不是count =+1
答案 1 :(得分:0)
check_solution
可能不应该是它自己的功能,但让我们解决这些问题:
正如yeniv所说:count =+1
是count = +1
或count = 1
,这显然不是你的意图。
check_solution
仅返回计数。您的else
也应该返回计数(可能未经修改)。
您不会对返回的计数执行任何操作:
check_solution(user_solution, solution, count)
应该是:
count = check_solution(user_solution, solution, count)
所以要解决当前代码中的问题:
def check_solution(user_solution, solution, count):
if user_solution == solution:
count =+1
print(count)
else:
print("Incorrect")
return count
请注意,函数中的count
变量和您称之为的count
变量不同。您可以更改函数中的名称并获得相同的结果:
def check_solution(user_solution, solution, func_count):
if user_solution == solution:
func_count =+1
print(func_count)
else:
print("Incorrect")
return func_count
当调用它时,你必须告诉python将结果放在哪里:
if index == 1:
solution = num_1 + num_2
num_1 = str(num_1)
num_2 = str(num_2)
problem = (num_1 + "+" + num_2)
user_solution = get_user_solution(problem)
count = check_solution(user_solution, solution, count)
return count
如果我自己写这篇文章,我会完全放弃该函数并使用正确的字符串格式化程序:
if index == 1:
solution = num_1 + num_2
problem = "%d+%d" % (num_1, num_2) # or %f if you're using floats
if solution == get_user_solution(problem):
count += 1
print(count)
else:
print("Incorrect")
return count