2016-03-02 98 views
2

我有一些代碼類似於此在while循環從定義函數訪問變量

v = '0' 

def program(): 
    x = input('1 or 2 ') 
    if x == '1': 
     print('it is 1') 
     v = '1' 
    elif x == '2': 
     print('it is 2') 
     v = '2' 

while True: 
    program() 
    print(v) 

然而,當我運行此代碼變量「V」總是打印出默認的0 爲什麼是不是它給了我在函數中賦值的變量?

+0

哪個版本您使用的使用raw_input在Python? – pzp

+1

你會在這裏找到一個很好的答案:http:// stackoverflow。com/questions/929777/why-do-assigning-to-my-global-variables-not-work-in-python –

回答

2

您有一個名爲v兩個變量:

  1. 頂部的全球v=0聲明。
  2. 程序中v的函數聲明。

首先,你真的不應該在函數中使用全局變量,因爲這是不好的編程習慣。您應該將其作爲參數傳遞並返回任何其他結果。

如果您確實需要,您可以通過首先將其聲明爲全局變量來修改函數中的全局變量。

另外請注意,你需要2

def program(): 
    global v 
    x = raw_input('1 or 2 ') 
    if x == '1': 
     print('it is 1') 
     v = '1' 
    elif x == '2': 
     print('it is 2') 
     v = '2' 

Using global variables in a function other than the one that created them

+1

很好的解釋。好的呼籲不好的做法提及。 – idjaw

1

您的函數操縱變量v的本地副本。如果要在調用program()之後獲得v的值,請將return v附加到函數定義的末尾。 那就是:

v = '0' 

def program(): 
    x = input('1 or 2 ') 
    if x == '1': 
     print('it is 1') 
     v = '1' 
    elif x == '2': 
     print('it is 2') 
     v = '2' 
    return v 

while True: 
    v = program() 
    print(v) 

如果你不想返回任何東西,你可以設置v到全局聲明變量像這樣:

v = '0' 

def program(): 
    x = input('1 or 2 ') 
    if x == '1': 
     print('it is 1') 
     global v 
     v = '1' 
    elif x == '2': 
     print('it is 2') 
     global v 
     v = '2' 

while True: 
    program() 
    print(v) 
1

爲了補充重複標誌,這裏是一個解釋關於你的代碼:

你需要明確地告訴你的方法,你想使用全局v,否則,它將永遠不會從發生的事情更新到v方法範圍。

爲了改善這種情況,您要添加global v你的方法裏面:

def program(): 
    global v 
    # rest of your code here 

這應該工作。

1

Python中的變量賦值在本地範圍內。如果你想在一個函數內部操縱一個全局狀態(或者一個封閉狀態),你可以把這個狀態包含在一個持有者中,然後引用持有者。例如:

v = ['0'] 

def program(): 
    x = input('1 or 2 ') 
    if x == '1': 
     print('it is 1') 
     v[0] = '1' 
    elif x == '2': 
     print('it is 2') 
     v[0] = '2' 

while True: 
    program() 
    print(v[0]) 

上面的段引用了一個數組並且操作​​了數組內的值。

+0

你可能想解釋一下如何改變變量的實際ID,而另一個只是修改對象該變量正在引用。 – pzp