从另一个函数获取变量的值

Getting the value of a variable from another function

我无法从问题函数中获取答案变量来检查答案是否确实正确。

以下是我目前所做的:

import random
import operator
a = 0
ops = {
    '+':operator.add,
    '-':operator.sub
}
def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion():
    guess = input("")
    if guess == a:
        print("Correct")
    else:
        print("Wrong, the answer is ", a)


generateQuestion()
askQuestion()

我删掉了一切正常的东西。

我知道我已经在顶部设置了 = 0,否则我会收到 未定义 错误。但是,我无法从 generateQuestion() 外部获得数学。

import random
import operator

ops = {
    '+':operator.add,
    '-':operator.sub
}

def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion(a):
    guess = input("")
    if guess == a:
        print("Correct")
    else:
        print("Wrong, the answer is ", a)

variable = generateQuestion()
askQuestion(variable)

您可以通过将答案值直接传递到 askQuestion 来减轻对全局的需要。

不要忘记将 return 从 input 转换为 int,如果你是 运行 python 3. 如果使用 python 2那么您就不需要 int 转换。

import random
import operator

ops = {
    '+':operator.add,
    '-':operator.sub
}

def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion(a):
    guess = input("")

    try:
        if int(guess) == a:
            print("Correct")
        else:
            print("Wrong, the answer is ", a)
    except:
        print('Did not input integer')

askQuestion(generateQuestion())

您遇到了范围问题。 generateQuestion 内部的变量 a 与外部 a 的变量 不同

为了解决这个问题,您需要在 generateQuestion.

中将 a 声明为全局
import random
import operator
a = 0
ops = {
    '+':operator.add,
    '-':operator.sub
}
def generateQuestion():
    x = random.randint(1, 10)
    y = random.randint(1, 10)
    op = random.choice(list(ops.keys()))
    global a
    a = ops.get(op)(x,y)
    print("What is {} {} {}?\n".format(x, op, y))
    return a

def askQuestion():
    guess = input("")
    if guess == a:
        print("Correct")
    else:
        print("Wrong, the answer is ", a)


generateQuestion()
askQuestion()

看看这个: http://nbviewer.ipython.org/github/rasbt/python_reference/blob/master/tutorials/scope_resolution_legb_rule.ipynb