NameError: name 'num' is not defined

NameError: name 'num' is not defined

def multiply(num):
    (num1 * num2)
    num1 = random.randint(1,12)
    num2 = random.randint(1,12) 
    if maths == "Multiplication" or "m" or "x": 
        ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))
    if ans == multiply(num1, num2):
        print("You are correct! ")
    else:
        print("Wrong, please try again. ")
    return num1 * num2

name = input("What is your name? ")
maths = input("What mathematics would you like to learn, " + name + "? ")
if maths == "Multiplication" or "m" or "x":
    multiply(num)

这行代码不断出现这个错误,我不确定为什么:

Traceback (most recent call last):
  File "program.py", line 15, in <module>
    multiply(num) 
NameError: name 'num' is not defined

有什么办法可以解决这个问题吗?

num 实际上并没有在 multiply() 中使用,所以没有理由传入它。相反,在没有参数的情况下声明 multiply()

def multiply():
    '''(num1 * num2)'''
    .
    .

然后像这样从 __main__ 调用它:

if maths == "Multiplication" or "m" or "x":
    multiply()

multiply() 中检查是否应该像下面这行那样执行乘法似乎没有意义:

if maths == "Multiplication" or "m" or "x":

然后您尝试递归调用 multiply(),但会失败:

if ans == multiply(num1, num2):

...只需使用 * 运算符。

最后,为什么return乘法的结果?如果在函数 multiply() 之外不知道被乘数,那么乘积有什么用? return 用户是否得到了正确答案可能会更好。

将以上所有内容放在一起,您会得到:

import random

def multiply():
    '''(num1 * num2)'''
    num1 = random.randint(1,12)
    num2 = random.randint(1,12)
    ans = int(input("What is the answer to " + str(num1) + " x " + str(num2) + " ? "))
    correct = (ans == num1 * num2)
    if correct:
        print("You are correct! ")
    else:
        print("Wrong, please try again. ")
    return correct

if __name__ == '__main__':
    name = input("What is your name? ")
    maths = input("What mathematics would you like to learn, " + name + "? ")
    if maths == "Multiplication" or "m" or "x":
        correct = multiply()