未定义全局变量x

时间:2013-09-10 14:39:19

标签: python python-3.3

现在这是我的问题,这是我的代码,位于下方。该程序找到了许多用户选择的根源。我的问题是,当我运行此代码时,NameError: global name 'x' is not defined。当首次遇到值main时,它来自x函数。我假设所有其他值都会发生同样的情况,所以基本上我想知道的是我是否必须在ValueGrabber函数之外定义这些值?或者我可以保留它的样子并稍微改变一下吗?

def ValueGraber():
    x = input("What number do you want to find the root of?:  ")
    root = input("Which root do you want to find?:  ")
    epsilon = input("What accuracy do you want the value to be to? e.g 0.01 :  ")
    high = float(x) + 1
    low = 0.0
    ans = (high + low)/2.0
    Perfect = None
    return x, root, epsilon, ans, high, low, Perfect

def RootFinder(x, root, epsilon, ans, high, low):
    while (ans**float(root)-float(x)) > epsilon and ans != float(x):
        if ans**float(root) > float(x):
        ans = high
        else:
        ans = high
            ans = (high + low)/2.0
    return ans

def PerfectChecker(ans, x, root, Perfect):
    if round(ans, 1)**float(root) == x:
        Perfect = True
    else:
        Perfect = False
    return Perfect

def Output(ans, x, root, perfect, epsilon):
    if Perfect == True:
        print("The number {0} has a perfect {1} root of    {2}".format(float(x),float(root),float(ans)))
    else:
        print("The root of the number {0} has a {1} root of {2} to an accuracy of {3}".format(float(x),float(root),float(ans),float(epsilon)))

def main():
    InputData = ValueGraber()
    DataOpp = RootFinder(x, root, epsilon, ans, high, low)
    PCheck = PerfectChecker(ans, x, root, Perfect)
    DataOutput = Output(ans, x, root, Perfect, epsilon)

main()

1 个答案:

答案 0 :(得分:3)

main中,您引用x但从未对其进行定义。

您的ValueGraber()函数确实返回值x,但该名称不会自动为调用者提供。

main()函数中的名称是 local ;在任何情况下,它们都不会自动反映从函数返回的名称。这是一个固定的main函数,只是发生使用与返回值函数相同的名称:

def main():    
    x, root, epsilon, ans, high, low, PerfecutData = ValueGraber()
    ans = RootFinder(x, root, epsilon, ans, high, low)
    Perfect = PerfectChecker(ans, x, root, Perfect)
    Output(ans, x, root, Perfect, epsilon)

我删除了DateOutput;它总是None,因为Output()不会返回任何内容。

您仍然可以在main中使用不同的名称; DataOpp是一个完全有效的本地名称(即使我个人会使用lower_case_with_underscores样式来表示本地名称),但是你不应该期望ans存在,你会使用{ {1}}中的任何地方{1}}代替。