2012-10-28 36 views
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 

我看到很多人有同樣的問題,但是當我在看什麼人告訴他們這樣做,我不能弄明白。無論如何,我的代碼是這樣的。我已經重新檢查了所有縮進,並且看不到它的問題。這個程序的目的是找到一個整數的主要因素(儘管它只完成了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 

在此先感謝您的幫助,

山姆

回答

6

在你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 % dividor0。例如,第一次testedInt是一個奇數,這會打你,例如,你的循環將永遠不會退出。

11爲例,你會嘗試除數1,23。雖然1是除數,但workingInt將保持11並且循環中斷。接下來for循環,除數是2,workingInt % 2是永遠不會給你0,所以循環將永遠持續下去。

+0

我希望它是一個變量,以便循環繼續前進,除非在阻止它的方法內部滿足條件。 –

+3

@SamHeather:正確的做法是使用'while True:'創建一個無限循環,然後當條件滿足時,使用'break'結束循環。 –

2

你需要以宣佈裏面one_cycle()全局變量xtestedIntworkingInt到那裏訪問它們:

def once_cycle(): 
    global x 
    global testedInt 
    global workingInt 
1

你需要在你的once_cycle()代碼來定義3 globals

作爲變量函數是靜態定義的,而不是函數被調用的時候。所以python認爲變量testedInt,workingIntx被函數視爲本地函數,並引發錯誤。

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

def once_cycle(): 
    global x 
    global workingInt 
    global testedInt 
    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()