David Hasselberg February 2016

Using variables from other functions in Python

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.

Answers


Marcus Müller February 2016

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


Rogalski February 2016

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.


Mike Müller February 2016

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)


k4ppa February 2016

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.

Post Status

Asked in February 2016
Viewed 3,775 times
Voted 5
Answered 4 times

Search




Leave an answer