我试图将一些代码放入一个函数中,但我得到了一个-我有点理解为什么,我只是不知道如何修复它。
编辑:具体来说,我被告知不要使用全局,因为全局“是一个坏主意”。肯定还有别的办法吗?
在整个代码中,我有多个需要由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发布于 2017-10-19 14:44:26
在您的职能中,首先是:
global Var1, Var2, Var3https://stackoverflow.com/questions/46832193
复制相似问题