Foxi
Foxi

Reputation: 3

Returning and reusing multiple variables in python

I have written a program opening and reading informations from a file, saving them in different variables, so they are easier to re-use after. I make it return them after, a bit like

return (Xcoord,Ycoord,Xrotation,Yrotation)

I after want to use them in another program, so I've tried calling the first one (let it be "prog1"), and then using them, like this:

def prog2():

prog1()

Xcoord.append(1)

I get a variable error, as I reference X before assignment. I've seen that I have to create a variable for my results, like x=prog1(), but what if I want to have several variables returned AND reused after?

Thanks in advance

Upvotes: 0

Views: 448

Answers (3)

gkusner
gkusner

Reputation: 1244

when you return multiple variables from a function it is actually returning a tuple so:

def func1():
    return x, y, z

x,y,z = func1()

thats it

Upvotes: 1

ykaganovich
ykaganovich

Reputation: 14964

Your question is really hard to parse, in part because you're using wrong terminology (functions are not programs). But I think you're asking about returning tuples from a function. That's doable:

def prog1():
  return (Xcoord,Ycoord,Xrotation,Yrotation)

def prog2():
  Xcoord, Ycoord, Xrotation, Yrotation = prog1()
  # do stuff with variables

Upvotes: 2

ForceBru
ForceBru

Reputation: 44828

Your function returns some variables, but you're not using them anywhere.

When you write a function like this:

def square(number):
    return number**2

You then call it like this:

squared=square(6)

Then squared will be equal to 36.


You should do exactly the same here:

Xc, Yc, Xrot, Yrot = prog1()

# use the returned variables
Xc.append(1)

Upvotes: 0

Related Questions