Python的烦人持久性错误:初学者

Sam*_*her 0 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
Run Code Online (Sandbox Code Playgroud)

我看到很多人都有同样的问题,但当我看到人们告诉他们要做的事情时,我无法理解.无论如何,我的代码是这样的.我已经重新检查了所有缩进,并且看不出它的问题.这个程序的目的是找到一个int的主要因素(虽然它只有90%完成).它是用Python 2.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
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助,

山姆

Mar*_*ers 6

在你的one_cycle()功能你在某个时刻分配到x:

        if (workingInt%dividor == 0):
            workingInt = workingInt/dividor
            x = 1
Run Code Online (Sandbox Code Playgroud)

这使得x局部变量.你也指的是一个测试:

    while x==0:
Run Code Online (Sandbox Code Playgroud)

但在此之前它被分配.这是您的例外原因.

无论是添加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
Run Code Online (Sandbox Code Playgroud)

或者,简化:

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()
Run Code Online (Sandbox Code Playgroud)

int(floating_point_number) 已经占据了浮点论证的底线.

需要注意的是你最终有一个无限循环,如果workingInt % dividor没有 0.第一次testedInt是一个奇数,例如,这将打击你,你的循环永远不会退出.

11,例如; 你会尝试的除数1,23.虽然1是一个除数,但workingInt仍然存在11并且循环中断.下一个for循环,除数是2,并且workingInt % 2永远不会给你0,所以循环将永远继续.

  • @SamHeather:正确的方法是使用`while True:`创建一个无限循环,然后当满足条件时,使用`break`来结束循环. (3认同)