Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use a returned variable from a previous function in another function? (python)

I want to use a list that was created from a previous function in my other function.
After a bit of research it seems using return is the way of doing it. However I cannot get it to work.
This is my code:

def FunctionA():
  all_comments1 = [1,2,3,4]
  return all_comments1

def FunctionB():
  FunctionA()
  all_comment_string1 = ''.join(all_comments1)
  newlistings1 = all_comment_string1.split('\n')
  print(newlistings1)

def DoSomething():
  FunctionB()

  DoSomething()

It gives me an error:

NameError: name ‘all_comments1’ is not defined

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I want to know how I can define the variable successfully.

>Solution :

You have to define a new variable. Right now you call the FunctionA() but don’t save its return value. To do so, simply make a new variable like so:

def FunctionA():
    all_comments1 = [1,2,3,4]
    return all_comments1

def FunctionB():
    all_comments = FunctionA()
    print(all_comments)

FunctionB()

>> [1,2,3,4]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading