想想Python练习5.2,检查费马

时间:2017-07-16 02:20:26

标签: python

要求用户输入a,b,c和n。 n必须大于2,所以我在checkn()中检查它。这样做可能是一种更为简单的方法;如果有,请告诉我!

追踪说"错误:姓名' n'未定义'。我假设我对局部和全局变量有些混淆,但我不确定如何解决我的这个错误。

我误解了什么?

这是我的代码:

import math

def fermat():
    if (a**n) + (b**n) == (c**n):
        print('Holy smokes, Fermat was wrong!')
    else:
        print("No, that doesn't work")

def checkn():
    print('insert n, must be greater than 2')
    n = int(input())
    if n <= 2:
        print('n must be greater than 2')
        checkn()
    else:
        fermat()

a = int(input('input a\n'))
b = int(input('input b\n'))
c = int(input('input c\n'))

checkn()

2 个答案:

答案 0 :(得分:1)

是。您正尝试访问本地作用域n变量到checkn函数。解决此问题的最简单方法是让fermat函数进行参数,然后在checkn函数中将n传递给fermat

定义fermat以接受争论:

我将参数更改为x只是为了帮助隔离n变量不相同的事实。您正在将值传递给函数。

def fermat(x):
    if (a**x) + (b**x) == (c**x):
        print('Holy smokes, Fermat was wrong!')
    else:
        print("No, that doesn't work")

checkn函数中,将n传递给fermat(仅显示相关部分):

    else:
        fermat(n)

答案 1 :(得分:0)

只是为了完成而添加。 (通过重构代码,您不必将任何变量传递给函数调用)

def fermat():
    N = powN;
    while N <= 2:
        N = int(input("Please enter pow > 2: \n"));
    if (a**N) + (b**N) == (c**N):
        print("Fermat is wrong my holy!!");
    else:
        print("That doesn't work");

a = int(input("Enter x: \n"));
b = int(input("Enter y: \n"));
c = int(input("Enter z: \n"));
powN = int(input("Enter pow: \n"));

fermat();
相关问题