cannot pass a variable from a function
Grégoire Dooms
dooms at info.LESS.ucl.SPAM.ac.be
Thu Jun 17 01:57:52 EDT 2004
If I understand well what you need:
>>> def f(a):
global q
q = a * 80
print q
>>> def g(l):
global q
for i in l:
q = i * 80
>>> q
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 Jordan wrote:
> 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
>
>
More information about the Python-list
mailing list