我刚刚开始学习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
提前谢谢你的帮助
山姆
您需要在
one_cycle()
内声明全局变量x
、testedInt
和workingInt
,以便在那里访问它们:在
one_cycle()
函数中,您在某个点分配给x
:这使得
x
成为局部变量。您还可以通过一个测试来引用它:但在分配给之前。这就是你例外的原因。你知道吗
要么在函数的开头添加
x = 0
,要么将其声明为全局(如果这是您的本意)。从外观上看,您没有在函数之外使用x
,所以您可能不是有意的。你知道吗以下工作;
workingInt
也正在修改,因此需要声明global
:或者,简化:
int(floating_point_number)
已经成为浮点参数的基础。你知道吗请注意,如果
workingInt % dividor
是而不是0
,则会得到一个无限循环。第一次testedInt
是一个奇数时,这会对您造成影响,例如,您的循环将永远不会退出。你知道吗以
11
为例,您将尝试除数1
、2
和3
。当1
是一个除数时,workingInt
将保持11
,循环将中断。下一个for
循环,除数是2
,而workingInt % 2
永远不会给你0
,因此循环将永远继续。你知道吗来自的
x
和我的不一样
有关如何在函数中使用全局变量的信息,请参见Using global variables in a function other than the one that created them。你知道吗
相关问题 更多 >
编程相关推荐