我想知道定义一个函数是否可以与另一个函数相关,所以它几乎就像一个连锁反应。使用以下公式,我希望它打印最终值,15。
我应该如何更改'second_formula'以识别'first_formula'中的值'c',依此类推。
def first_formula():
a = 1
b = 2
c = a + b
second_formula()
def second_formula():
d = 4
e = c + d
third_formula()
def third_formula():
f = 8
g = e + f
print (g)
first_formula()
答案 0 :(得分:0)
您可以使用参数:
def first_formula():
a = 1
b = 2
c = a + b
second_formula(c)
def second_formula(c):
d = 4
e = c + d
third_formula(e)
def third_formula(e):
f = 8
g = e + f
print (g)
first_formula()
另外, I BELIEVE ,如果在同一个文件中执行,我认为你的方法可以工作(但我认为你必须在def之外创建变量):
c,e = 0,0 # Their are the 'specials variables'
first_formula()
答案 1 :(得分:0)
将其作为参数传递。
def first_formula():
a = 1
b = 2
c = a + b
second_formula(c)
def second_formula(c):
d = 4
e = c + d
third_formula(e)
def third_formula(e):
f = 8
g = e + f
print (g)
first_formula()
然而,如果你让每个函数都返回它的结果,这会更好;让调用程序决定应该去哪里:
def first_formula():
a = 1
b = 2
return a+b
def second_formula():
d = 4
return d + first_formula()
def third_formula():
f = 8
return f + second_formula()
print(third_formula())
这有帮助吗?