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

Question:

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

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

Asked By: RonaLightfoot

||

Answers:

You just called a function.Do something with it.

Answered By: epiciby

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]
Answered By: Miha

I believe you are looking to use global variables between your functions. Modify your code to the following:

def FunctionA():
    # Declare all_comments1 as a global variable
    global all_comments1
    all_comments1 = [1, 2, 3, 4]
    return all_comments1


def FunctionB():
    # Access global variable
    global all_comments1
    # Run functionA otherwise global variable will not be defined
    FunctionA()

    # Map objects from `all_comments1` to str, since they are int
    all_comment_string1 = ''.join(map(str, all_comments1))
    newlistings1 = all_comment_string1.split('n')
    print(newlistings1)

def DoSomething():
    FunctionB()

DoSomething()

>> ['1234']
Answered By: Yaakov Bressler
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.