0

I'm new to Python. My codes are similar to this example:

banana = ps.Series(x)

def chocolate(co):
    co=math.sqrt(co)
    if co > 10:
       milk = co - 5
    else:
       milk = co + 5

and i want to take the milk value to be calculated again outside the function like this:

chocolate(banana)
banana_milk=banana.pow(milk)

I've tried it and got NameError: name 'milk' is not defined. How to fix it? should i use class? if i use class, i still don't get where to put the 'milk' definition

Please don't ask me to do all outside the function. My code is more complicated than the example.

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
irene G
  • 3
  • 1
  • 2
    Just return it. – quamrana Aug 21 '22 at 13:39
  • i'm sorry i got typo, i mean `banana = pd.Series(x)` – irene G Aug 21 '22 at 13:39
  • 4
    Add `return milk` to your function to return the *value* that `milk` references, then use `milk = chocolate(banana)` to then store the returned value in a new (global) `milk` variable. Or you can name that differently: `chocolate_milk = chocolate(banana)` and `banana_milk = banana.pow(chocolate_milk)`. – Martijn Pieters Aug 21 '22 at 13:40

1 Answers1

-2
banana = ps.Series(x)

milk = 0

def chocolate(co):
    global milk
    co=math.sqrt(co)
    if co > 10:
       milk = co - 5
    else:
       milk = co + 5

Don't go too crazy with the globals however, it is generally looked down upon.

nigel239
  • 1,485
  • 1
  • 3
  • 23