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
有没有办法解决这个问题?
答案 0 :(得分:2)
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):
...只需使用*
运算符。
最后,为什么要返回乘法的结果?如果在函数multiply()
之外不知道被乘数,那么该产品有什么用?回到用户是否得到正确的答案可能会更好。
将上述所有内容放在一起,你就明白了:
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()