Python 3.x:如何操作所有函数中的变量? (W/O全球)(UnboundLocalError)
问题描述:
我试图把一些代码放入一个函数,但我得到一个未绑定的本地错误 - 我有点理解为什么,我只是不知道如何解决它。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
答
在你的函数,先从:
global Var1, Var2, Var3
唯一的Python的方式是使用'全球'关键字 –
没有全球性会怎样?全球有副作用,不是吗? – CoderBaby