我是一名學生,剛剛開始學習代碼。現在,我使用Python和有一個程序,我認爲應該工作,但只是返回一些錯誤,我不明白:初學者試圖調試一個簡單的程序
Traceback (most recent call last): File "C:\Program Files\Notepad++\1913lab3.py", line 23, in print(most(odd, []))
File "C:\Program Files\Notepad++\1913lab3.py", line 9, in most N = S[i] UnboundLocalError: local variable 'i' referenced before assignment
我不明白的第一個錯誤告訴我,但我想我理解第二個,但我不明白爲什麼我會得到它。我不認爲我是一個局部變量,因爲我一開始就定義了它。代碼如下:
t = 0
f = 0
i = 0
def odd(N):
return N % 2 != 0
def most(P, S):
N = S[i]
if P == True:
t += 1
else:
f += 1
i += 1
if i < len(S):
most(P, S)
else:
if t > f:
return 'True'
else:
return 'False'
print(most(odd, []))
print(most(odd, [0]))
print(most(odd, [1]))
print(most(odd, [1, 2]))
print(most(odd, [1, 2, 3]))
該賦值是定義一個遞歸函數(most())。該函數使用一個函數和一個列表作爲它的參數(P和S)。我不能使用循環或局部變量。下面是從分配報價:
"P is a function of one argument that returns either True or False, and S is a list. The function most calls P on each element of S. It must return True if P returns True more often than it returns False. It must return False otherwise."
5個打印命令僅有5例子,我需要爲信貸工作,但這個方案需要爲所有列表工作。如果有人能幫我解決這些錯誤,那會很棒。 (另外,歡迎任何一般的Python提示。)
看看這個答案:http://stackoverflow.com/questions/10851906/python-3-unboundlocalerror-local-variable-referenced-before-assignment#10852003 – Jackowski
看看這個問題:(http:// stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them)。你的問題是你試圖在函數內部修改全局變量,但是由於python並沒有讓你在使用它們之前聲明你的變量,所以python沒有辦法知道你是否應該使用函數中的變量來解釋創建一個只存在於函數內部的新變量,或者如果你的意思是具有該名稱的全局變量。 –
@Amorpheuses但是他在全球定義了'i',這可能導致他相信他正在使用「全局」'i'變量。此外,您的評論有點粗魯... –