-1

I want to know if defining a function can be related to another function, so it's almost like a chain reaction. With the following formulas, I want it to print the final value, 15.

How should I change this for 'second_formula' to recognize the value 'c' from the 'first_formula', and so on.

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()
Prune
  • 76,765
  • 14
  • 60
  • 81
Johnny Kang
  • 145
  • 1
  • 12
  • You'll need to add an argument. For example, `def second_formula(c):`, then you would call it in `first_formula` as `second_formula(c)`. – zondo Apr 06 '17 at 00:34

2 Answers2

0

You can use arguments:

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()

Also, I BELIEVE, that if there are executed in the same file, i think that your method could work (but i think that you have to create the variables outside the def):

c,e = 0,0 # Their are the 'specials variables'
first_formula()
Prune
  • 76,765
  • 14
  • 60
  • 81
Ender Look
  • 2,303
  • 2
  • 17
  • 41
0

Pass it as a parameter.

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()

However, this would be even better if you'd have each function return its result; let the calling program decide where it should go:

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())

Does that help?

Prune
  • 76,765
  • 14
  • 60
  • 81