cannot pass a variable from a function

D

Doug Jordan

I am fairly new to Python. This should be an easy answer but I cannot get
this to work. The code is listed below. I know how to do this in C,
Fortran, and VB but it doesn't seem to work the same way here.
I would appreciate any help.

#try this to pass a list to a function and have the function return
#a variable
#this works
list=[1,4,6,9]
def fctn(c):
for h in c:
q=h*80
print q
#function suppose to return variable
def fctn2(c):
for h in c:
q=h*80
return q
def prntfctn(y):
for j in y:
print j
fctn(list)
fctn2(list)
prntfctn(q)

I need to be able to return variables from functions so they can be used
globally in the rest of the program I am writing.
Thanks

Doug
 
K

Kirk Strauser

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Doug Jordan said:
#function suppose to return variable
def fctn2(c):
for h in c:
q=h*80
return q

def prntfctn(y):
for j in y:
print j

fctn2(list)
prntfctn(q)

The name "q" only exists inside the scope of the fctn2 variable. If you
want it present inside the global scope, assign it there:

q = fctn2(list)
prtnfctn(q)

That should do what you want. Note that I'm unaware of any modern
programming language that would allow a function to assign a value to a
global variable without explicitly requesting it. If such a thing exists,
then I highly recommend you avoid it at all costs.
- --
Kirk Strauser
The Strauser Group
Open. Solutions. Simple.
http://www.strausergroup.com/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFA0NS95sRg+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkEmA8BDSEgCaAgcp
u44PX2uPlSMGYAV4VG5jaC8=
=G3qn
-----END PGP SIGNATURE-----
 
D

Doug Jordan

Kirk,
Thanks for your input, hoever that is not exactly what I am trying to do.
I understand that q is local scope. I was trying to return q and make a
call to the function using another variable with global scope.

In other language
subroutine foo(b,c)
c=b*1000
return
call foo(q,r)
where q and r are defines and same type as b,c as function
How do I do this in python. I need to perform operations on a variable and
pass the new variable to the program.
Hope this might clear it up.

Doug
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Doug Jordan said:
#function suppose to return variable
def fctn2(c):
for h in c:
q=h*80
return q

def prntfctn(y):
for j in y:
print j

fctn2(list)
prntfctn(q)

The name "q" only exists inside the scope of the fctn2 variable. If you
want it present inside the global scope, assign it there:

q = fctn2(list)
prtnfctn(q)

That should do what you want. Note that I'm unaware of any modern
programming language that would allow a function to assign a value to a
global variable without explicitly requesting it. If such a thing exists,
then I highly recommend you avoid it at all costs.
- --
Kirk Strauser
The Strauser Group
Open. Solutions. Simple.
http://www.strausergroup.com/
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.2.4 (GNU/Linux)

iD8DBQFA0NS95sRg+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkEmA8BDSEgCaAgcp
u44PX2uPlSMGYAV4VG5jaC8=
=G3qn
-----END PGP SIGNATURE-----
 
L

Larry Bates

Doug,

You are talking about passing by reference. Python
doesn't do that. It only passes by value, unless you
pass an object (e.g. list, dictionary, class, etc.).
In those cases you CAN modify object in the function.

For simple operations, just return the value an use
it later (like Fortran functions).

def foo(b)
return b*1000

c=foo(b)

objects can be passed and modified

def foo(b, l)
l.append(b)
return

l=[]
foo(1)
l->[1]
foo(2)
l->[1,2]
foo('test')
l->[1,2,'test']

HTH,
Larry Bates
Syscon, Inc.
 
P

Porky Pig Jr

Doug Jordan said:
I am fairly new to Python. This should be an easy answer but I cannot get
this to work. The code is listed below. I know how to do this in C,
Fortran, and VB but it doesn't seem to work the same way here.
I would appreciate any help.

#try this to pass a list to a function and have the function return
#a variable
#this works
list=[1,4,6,9]
def fctn(c):
for h in c:
q=h*80
print q

You know, I am also new to Python, and fairly well versed in C, but
don't you think that the following function:
#function suppose to return variable
def fctn2(c):
for h in c:
q=h*80
return q

will return whatever it gets on a very first iteration so it will
return a scalar 1*80 rather than list I assume you are trying to
return.
You probably need something like this:
def fctn2(c):
return [h * 80 for h in c]



Once again, you didn't make it quite clear what is that exaclty you
are trying to return, so I assume you are trying to return a list,
rather than scalar.
 
?

=?ISO-8859-1?Q?Gr=E9goire_Dooms?=

If I understand well what you need: global q
q = a * 80
print q
global q
for i in l:
q = i * 80


Traceback (most recent call last):
File "<pyshell#18>", line 1, in -toplevel-
q
NameError: name 'q' is not defined
>>> f(5) 400
>>> q 400
>>> g([1,2,3])
>>> q 240
>>>


However using global variables is a bad habit and you should restrain
from doing it. Why not pass q to every of these functions and have them
return the new value of q ?

--
Grégoire Dooms

Doug said:
I am fairly new to Python. This should be an easy answer but I cannot get
this to work. The code is listed below. I know how to do this in C,
Fortran, and VB but it doesn't seem to work the same way here.
I would appreciate any help.

#try this to pass a list to a function and have the function return
#a variable
#this works
list=[1,4,6,9]
def fctn(c):
for h in c:
q=h*80
print q
#function suppose to return variable
def fctn2(c):
for h in c:
q=h*80
return q
def prntfctn(y):
for j in y:
print j
fctn(list)
fctn2(list)
prntfctn(q)

I need to be able to return variables from functions so they can be used
globally in the rest of the program I am writing.
Thanks

Doug
 
?

=?ISO-8859-1?Q?Gr=E9goire_Dooms?=

Grégoire Dooms said:
If I understand well what you need:
global q
q = a * 80
print q

global q
for i in l:
q = i * 80

But this should better be implemented as
def g(l):
global q
q = l[-1] * 80

Even better:

def g(q,l):
return l[-1] * 80
# and use as
q = g(q,l)
 
M

Miki Tebeka

Hello Doug,
In other language
subroutine foo(b,c)
c=b*1000
return
call foo(q,r)
where q and r are defines and same type as b,c as function
How do I do this in python. I need to perform operations on a variable and
pass the new variable to the program.
I think you mean "call by reference". In this case you can only modify
"compound" types (there is a better word for this) such as lists, has
tables ...
If you do:
def f(l):
l.append(1)

a = []
f(a) # a -> [1]

However you can't do that to "simple" types such as int, long ...
def f(x):
x += 2
a = 1
f(a) # a -> 1

IMO this is not a problem since in Python you can returns multiple
values and less side effects = less bugs.

If you *must* do this you can wrap your variables:
def f(x):
x.a += 2

class P:
pass
p = P()
p.a = 1
f(p) # p.a -> 3


HTH.

Bye.
 
S

Steve

Larry Bates wrote:

Doug,

You are talking about passing by reference. Python
doesn't do that. It only passes by value, unless you
pass an object (e.g. list, dictionary, class, etc.).
In those cases you CAN modify object in the function.

I think this is horribly horribly confused and
confusing and I wish I had never learnt Pascal so that
this reference/value wossname wouldn't contaminate my
thinking. Python doesn't have pointers, thank Offler.

If you google on "pass by reference" and "pass by
value" you will quickly discover that whenever you have
two programmers in a room and ask them to describe
whether a language is one or the other, you will get
three different opinions.

To give an example of why it is so confusing, a pointer
in C has two values, the value of the pointer and the
value of the thing the pointer points to. Let the C
programmers deal with that, we don't have to.

I believe that Tim Peters once declared that Python was
"call by object":

'''I usually say Python does "call by object". Then
people go "hmm, what's that?". If you say "call by
XXX" instead, then the inevitable outcome is a
tedious demonstration that it's not what *they*
mean by XXX. Instead I get to hear impassioned
arguments that "by object" is what any normal person
means by YYY <wink>.'''


Well, that's sweet, but since I don't read whatever
language this comes from, I don't know what it is
returning. Does it return c? Or perhaps b? A nil
pointer? Some special value indicating no result?

It looks to me like the value of c gets immediately
over-written, so why pass it to the function in the
first place?

The nice thing about Python is that it is explicit
instead of implicit. If you want to return something,
you have to return it.

(The only exception is, if you don't return anything,
you actually return None. *cough*)

def foo(b, c):
# return modified c
c = b*1000
return c

If we go all the way back to your original request, my
understanding was that you wanted to modify the
following to return something:

But what is it that you are expecting to return? The
last value of y? The first? Everything in y?

def prnt_and_return(y):
# print each item in list y and return the
# entire list with a minus one appended
for item in y:
print item
return y + [-1]
>>> y = [1, 2, 3]
>>> z = prnt_and_return(y)
1
2
3
[1, 2, 3], [1, 2, 3, -1]



Regards,
 
D

Doug Jordan

this seems to work only if c in def(c) is a list. I have a tuple of tuples.
I need to operate on one of the members of adata pair and return a new tuple
of tuples to be used later in the program.

if I use the following, it only returns 1 value.
tup1=((1,3),(2,5),(3,9))
def NewFctn(c):
for a,b in c:
v=b*9
return v
y=NewFctn(tup1)

what I need is to return v as a tuple of tuples to be used later in the
program. How do I do this. I cannot find any information on this.
This is needed because I need to perform some operations on the second
member of data pairs stored as a tuple of tuples. This is needed to post
process output from a commercial program(ABAQUS)
ie.
Output variable might contain
((t1,F1),(t2,F2)..(tn,Fn)) I want to perform operations on Fi
Thanks
Sorry about all the confusion
Doug
Porky Pig Jr said:
"Doug Jordan" <[email protected]> wrote in message
I am fairly new to Python. This should be an easy answer but I cannot get
this to work. The code is listed below. I know how to do this in C,
Fortran, and VB but it doesn't seem to work the same way here.
I would appreciate any help.

#try this to pass a list to a function and have the function return
#a variable
#this works
list=[1,4,6,9]
def fctn(c):
for h in c:
q=h*80
print q

You know, I am also new to Python, and fairly well versed in C, but
don't you think that the following function:
#function suppose to return variable
def fctn2(c):
for h in c:
q=h*80
return q

will return whatever it gets on a very first iteration so it will
return a scalar 1*80 rather than list I assume you are trying to
return.
You probably need something like this:
def fctn2(c):
return [h * 80 for h in c]



Once again, you didn't make it quite clear what is that exaclty you
are trying to return, so I assume you are trying to return a list,
rather than scalar.
 
?

=?iso-8859-15?Q?Pierre-Fr=E9d=E9ric_Caillaud?=

if I use the following, it only returns 1 value.
tup1=((1,3),(2,5),(3,9))
def NewFctn(c):
for a,b in c:
v=b*9
return v
y=NewFctn(tup1)

Well of course.
Your function returns during the first iteration of the for loop.
You need to put this return after the end of the for loop so the loop
loops through all values in c.
I don't really understand what you want so my suggestion could be bad.

Suggestion :

if you want to apply a function to all tuples in your list, use map :

map( lambda tup: (tup[0], tup[1]*9), tupl )

or :

def funct( tuples ):
rval = []
for a,b in tuples:
rval.append( ( a, b*9 ))
return tuple(rval)

or :

tuple( [ (a,b*9) for a,b in tuples ] )
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top