Stack Overflow 社区您好,
我正在尝试编写一个程序来检查费马大定理。我遇到的问题是出现错误,显示“NameError:名称'a'未定义。但是,我在第一个函数中定义了'a'并在函数末尾返回其值。
我尝试在第二个函数中使用第一个函数输入的值,以便用户可以定义参数。
我是否误解了如何利用“返回”?非常感谢所有帮助,并使我保持理智。
def input_fermat():
a=input('Enter the first variable \'a\': \n')
b=input('Enter the second variable \'b\': \n')
c=input('Enter the third variable \'c\': \n')
n=input('Enter the exponential variable \'n\': \n')
return a, b, c, n
def check_fermat(a,b,c,n):
calc_1=a**n
calc_2=b**n
calc_3=c**n
if n>2 and int(calc_1) + int(calc_2) == calc_3:
print('Holy smokes, Fermat was wrong!')
else:
print('No that doesn\'t work.')
input_fermat()
check_fermat(a,b,c,n)
最佳答案
在 input_fermat
中定义的变量 a, b, c, n
仅存在于函数内,这就是您返回它们的原因,但是当您调用该函数时,您就不再存在了不要将它们保存在任何地方。您应该替换:
input_fermat()
作者:
a, b, c, n = input_fermat()
或者您可以直接将 input_fermat
的返回值传递给 check_fermat
,如下所示:
check_fermat(*input_fermat())
关于Python:返回可能不返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53347740/