2017-10-19 96 views
0

我試圖把一些代碼放入一個函數,但我得到一個未綁定的本地錯誤 - 我有點理解爲什麼,我只是不知道如何解決它。Python 3.x:如何操作所有函數中的變量? (W/O全球)(UnboundLocalError)

編輯:特別是我被告知不要使用全球,因爲全球「是一個壞主意」。當然必須有另一種方式?

在整個代碼中,我有多個變量需要通過user_input進行更改,然後需要通過一個或多個不同的函數(重複(使用新值)直到得出特定結論)。

如何在多個函數中使用變量(乾淨地)?如果我在一個函數中定義它們,那麼它們只在那裏可用,對吧?我不能從其他地方改變他們的價值觀?

謝謝你的幫助。

這是代碼的素描時,我想提出一個功能:

#variables that need to be used (and altered) within multiple functions 
Var1 = #a_number 
Var2 = #a_number 
Var3 = #a_number 

def a_function(): #created Unbound Local Error 
    output() #prints original vars 
    while True: 
     inp = float(input("Enter a number: ")) 

     Var1 += inp 
     Var2 -= inp 
     Var3 *= inp 
     output() #prints new values for vars 

     if/elif/else.... 
     #when Vars are a certain number new calculations are done 
     #on them. Regardless, there is always only one output of 
     # the 3 Vars 
     #some Var vals trigger certain functs which print those new value 
     #or functions which may even manipulate the values further 
+0

唯一的Python的方式是使用'全球'關鍵字 –

+0

沒有全球性會怎樣?全球有副作用,不是嗎? – CoderBaby

回答

1

在你的函數,先從:

global Var1, Var2, Var3