Using variables from other functions in Python

Question:

I am learning python and am currently writing a simple program that has to be divided into functions. My problem is that I have one function that should return strings for four different variables, that then should be used in another function.

E.g.

def function1():
   var1 = input("Write something: ")
   var2 = input("Write something: ")
   var3 = input("Write something: ")

def function2():
   print(var1)
   print(var2)
   print(var3)

function1()
function2()

This gives an error message since var1 is not defined in the frame of function2. How should this be solved? The illustration is very simplified for clarity, but I could post something more specific if required.

Asked By: David Hasselberg

||

Answers:

That’s not what functions are for.

There is a thing called scoping, which basically says that variables declared within a function are local to that function and can’t be accessed by anything else. If you need to pass values to a function, use parameters.

This should all be covered by the Python introduction you’re probably currently reading — just read on one or two pages 🙂

Answered By: Marcus Müller

Correct approach would be to return values from functions and pass them via input arguments:

def function1():
    var1 = input("Write something: ")
    var2 = input("Write something: ")
    var3 = input("Write something: ")
    return var1, var2, var3


def function2(a, b, c):
    print(a)
    print(b)
    print(c)

v1, v2, v3 = function1()
function2(v1, v2, v3)

I renamed some of parameters to emphasize that there is no name relation anywhere. All values are explicitly returned and explicitly passed.

Answered By: Łukasz Rogalski

Return the variables in function1:

def function1():
    var1 = input("Write something: ")
    var2 = input("Write something: ")
    var3 = input("Write something: ")
    return var1, var2, var3

and make them arguments in function2:

def function2(var1, var2, var3):
    print(var1)
    print(var2)
    print(var3)

Call them like this:

var1, var2, var3 = function1()
function2(var1, var2, var3)
Answered By: Mike Müller

With your current example the better approach is reuse the same functions three times:

def function1():
    return input("Write something: ")

def function2(var):
   print(var)

for i in range(0, 3):
    var = function1()
    function2(var)

But it may be better return the variables in function1 and then pass it to function2.

def function1():
   var1 = input("Write something: ")
   var2 = input("Write something: ")
   var3 = input("Write something: ")
   return var1, var2, var3

def function2(var1, var2, var3):
   print(var1)
   print(var2)
   print(var3)

var1, var2, var3 = function1()
function2(var1, var2, var3)

It depends on your specific problem.

Answered By: k4ppa
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.