2015-05-19 20 views
-3

我該如何定義一個在函數範圍內聲明的布爾變量?如何在Python中的函數定義內部定義布爾值?

我已經定義在下面的函數變量pass = True,函數定義中的處於if語句設置它的值:

def test(array, n): # Define the function test with input parameters array and n 
    pass = True # Initialize variable pass to the boolean value True 
    for i in n: # For n number of times, perform the following operation using i as a counter 
     for j in range(i+1,n): # Increment from i+1 to n using j as a counter 
     if(array[i] == array[j]): # If the ith element in array equals the jth element, execute the following code 
               # If one element is equivalent to any subsequent 
               # elements of the array, set pass = true 
      pass = False # define pass as false 

return pass # return pass 
+1

該代碼看起來是正確的,雖然有些線路是不縮進正確。這是你的問題還是你複製/粘貼錯誤,並有另一個問題? – rlbond

+4

達到這樣的事實,即:1.你不使用python周圍的parensis if語句。 2.「pass」是python中的一個關鍵字,你試圖覆蓋它,爲變量選擇不同的名字 – lejlot

+5

@lejlot'pass'是一個關鍵字,所以這個程序甚至不會編譯。 –

回答

2

除了一些壓痕問題,我認爲是由於SO張貼和不是由於真正的代碼被錯誤縮進,問題是pass是python中的保留字 - 它是空操作。如果你有一個合法的標識符替換它(例如,shouldPass),你應該罰款:

def test(array, n): # Define the function test with input parameters array and n 
    shouldPass = True # Initialize variable shouldPass to the boolean value True 
    for i in n: # For n number of times, perform the following operation using i as a counter 
     for j in range(i+1,n): # Increment from i+1 to n using j as a counter 
      if array[i] == array[j]: # If the ith element in array equals the jth element, execute the following code 
               # If one element is equivalent to any subsequent 
               # elements of the array, set shouldPass = true 
       shouldPass = False # define shouldPass as false 

    return shouldPass # return shouldPass 
+0

而'n'看起來不像一個可迭代的,它們循環着,然後傳遞給'range()'。我想他們的意思是:'對於我在範圍(n):' –

+0

我沒有深入研究函數的「業務邏輯」,只是語法問題。 – Mureinik

+1

考慮到他們並沒有關心發佈任何回溯,他們的下一個評論將是:「它仍然無法正常工作」。 ;-) –