Python的恼人的持久性错误:Beginn

2024-09-28 01:23:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始学习python,不断地遇到一个我无法理解的错误。任何帮助都将不胜感激。基本上,我一直得到以下错误:

Enter an int: 8

Traceback (most recent call last):
  File "C:\Users\Samuel\Documents\Python Stuff\Find Prime Factors of Number.py", line 16, in <module>
    once_cycle()
  File "C:\Users\Samuel\Documents\Python Stuff\Find Prime Factors of Number.py", line 8, in once_cycle
    while x==0:
UnboundLocalError: local variable 'x' referenced before assignment

我看到很多人都有同样的问题,但当我看到人们告诉他们做什么,我就想不出来了。不管怎样,我的代码是这样的。我重新检查了所有的压痕,看不出有什么问题。这个程序的目的是找出整数的素因子(尽管它只完成了90%)。它是用python2.7.3编写的。你知道吗

import math
testedInt = float(raw_input("Enter an int: "))
workingInt = testedInt
x = 0

def once_cycle():
    for dividor in range(1, int(math.floor(math.sqrt(testedInt))+1)):
        while x==0:
            print "Called"
            if (workingInt%dividor == 0):
                workingInt = workingInt/dividor
                x = 1
    if (workingInt > 1):
        once_cycle()
    return

once_cycle()

print workingInt

提前谢谢你的帮助

山姆


Tags: inan错误mathusersdocumentsfileint
3条回答

您需要在one_cycle()内声明全局变量xtestedIntworkingInt,以便在那里访问它们:

def once_cycle():
    global x
    global testedInt
    global workingInt

one_cycle()函数中,您在某个点分配给x

        if (workingInt%dividor == 0):
            workingInt = workingInt/dividor
            x = 1

这使得x成为局部变量。您还可以通过一个测试来引用它:

    while x==0:

但在分配给之前。这就是你例外的原因。你知道吗

要么在函数的开头添加x = 0,要么将其声明为全局(如果这是您的本意)。从外观上看,您没有在函数之外使用x,所以您可能不是有意的。你知道吗

以下工作;workingInt也正在修改,因此需要声明global

def once_cycle():
    global workingInt
    x = 0

    for dividor in range(1, int(math.floor(math.sqrt(testedInt))+1)):
        while x==0:
            print "Called"
            if (workingInt%dividor == 0):
                workingInt = workingInt/dividor
                x = 1
    if (workingInt > 1):
        once_cycle()
    return

或者,简化:

def once_cycle():
    global workingInt

    for dividor in range(1, int(math.sqrt(testedInt)) + 1):
        while True:
            if workingInt % dividor == 0:
                workingInt = workingInt / dividor
                break
    if workingInt > 1:
        once_cycle()

int(floating_point_number)已经成为浮点参数的基础。你知道吗

请注意,如果workingInt % dividor而不是0,则会得到一个无限循环。第一次testedInt是一个奇数时,这会对您造成影响,例如,您的循环将永远不会退出。你知道吗

11为例,您将尝试除数123。当1是一个除数时,workingInt将保持11,循环将中断。下一个for循环,除数是2,而workingInt % 2永远不会给你0,因此循环将永远继续。你知道吗

来自的x

x = 0

和我的不一样

while x==0:

有关如何在函数中使用全局变量的信息,请参见Using global variables in a function other than the one that created them。你知道吗

相关问题 更多 >

    热门问题