条件没有传入if语句

时间:2017-04-30 09:36:53

标签: python if-statement conditional-statements

我每次运行该函数时都试图增加计数,似乎每次运行该函数时都会重置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

2 个答案:

答案 0 :(得分:2)

声明应该是count += 1而不是count =+1

答案 1 :(得分:0)

check_solution可能不应该是它自己的功能,但让我们解决这些问题:

  • 正如yeniv所说:count =+1count = +1count = 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