473,326 Members | 2,126 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,326 software developers and data experts.

cannot pass a variable from a function

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
Jul 18 '05 #1
10 2036
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-06-16T22:46:42Z, "Doug Jordan" <dj******@houston.rr.com> writes:
#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+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkE mA8BDSEgCaAgcp
u44PX2uPlSMGYAV4VG5jaC8=
=G3qn
-----END PGP SIGNATURE-----
Jul 18 '05 #2
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
"Kirk Strauser" <ki**@strauser.com> wrote in message
news:87************@strauser.com...
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-06-16T22:46:42Z, "Doug Jordan" <dj******@houston.rr.com> writes:
#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+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkE mA8BDSEgCaAgcp
u44PX2uPlSMGYAV4VG5jaC8=
=G3qn
-----END PGP SIGNATURE-----
Jul 18 '05 #3
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.

"Doug Jordan" <dj******@houston.rr.com> wrote in message
news:51***************@fe2.texas.rr.com...
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
"Kirk Strauser" <ki**@strauser.com> wrote in message
news:87************@strauser.com...
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-06-16T22:46:42Z, "Doug Jordan" <dj******@houston.rr.com> writes:
#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+Y0CpvERAlGRAKCkUJTaBJIckaWCvM2qkE mA8BDSEgCaAgcp
u44PX2uPlSMGYAV4VG5jaC8=
=G3qn
-----END PGP SIGNATURE-----

Jul 18 '05 #4
"Doug Jordan" <dj******@houston.rr.com> wrote in message news:<m5****************@fe2.texas.rr.com>...
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.
Jul 18 '05 #5
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

Jul 18 '05 #6
Grégoire Dooms wrote:
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


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)

--
Grégoire Dooms
Jul 18 '05 #7
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>.'''

Earlier, Doug Jordan wrote:
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.
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:
def prntfctn(y):
for j in y:
print j
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 print y, z

[1, 2, 3], [1, 2, 3, -1]

Regards,

--
Steven.


Jul 18 '05 #8
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.
--
-------------------------------------------------------------------------
Miki Tebeka <mi*********@zoran.com>
The only difference between children and adults is the price of the toys.

Jul 18 '05 #9
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" <po**********@my-deja.com> wrote in message
news:56*************************@posting.google.co m...
"Doug Jordan" <dj******@houston.rr.com> wrote in message

news:<m5****************@fe2.texas.rr.com>...
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.

Jul 18 '05 #10
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 ] )

Jul 18 '05 #11

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Seeker | last post by:
Newbie question here... I have a form with some radio buttons. To verify that at least one of the buttons was chosen I use the following code ("f" is my form object) : var btnChosen; for...
8
by: Vijay | last post by:
Hi all, Im using gcc version 3.2.3 20030502 (Red Hat Linux 3.2.3-20) on 64bit linux server im trying to compile following code --------------------sam.cpp--------------------- #include...
8
by: baustin75 | last post by:
Posted: Mon Oct 03, 2005 1:41 pm Post subject: cannot mail() in ie only when debugging in php designer 2005 -------------------------------------------------------------------------------- ...
10
by: Jean-David Beyer | last post by:
I have some programs running on Red Hat Linux 7.3 working with IBM DB2 V6.1 (with all the FixPacks) on my old machine. I have just installed IBM DB2 V8.1 on this (new) machine running Red Hat...
2
by: Matthew Louden | last post by:
When I pass an array as a function parameter, it yields the following compile error. Any ideas?? However, if I create a variable that holds an array, and pass that variable to the function...
4
by: kishor | last post by:
I have an activeX dll, I am calling one function from that dll. I am using C# as coding language. I am getting following error. cannot convert from 'string' to 'ref string' How do I call this...
45
by: Zytan | last post by:
This returns the following error: "Cannot modify the return value of 'System.Collections.Generic.List<MyStruct>.this' because it is not a variable" and I have no idea why! Do lists return copies...
10
by: Robert Dailey | last post by:
Hi, I noticed in Python all function parameters seem to be passed by reference. This means that when I modify the value of a variable of a function, the value of the variable externally from the...
12
by: Bryan Parkoff | last post by:
I write my large project in C++ source code. My C++ source code contains approximate four thousand small functions. Most of them are inline. I define variables and functions in the global scope....
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.