473,654 Members | 3,062 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 2060
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-06-16T22:46:42Z, "Doug Jordan" <dj******@houst on.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)

iD8DBQFA0NS95sR g+Y0CpvERAlGRAK CkUJTaBJIckaWCv M2qkEmA8BDSEgCa Agcp
u44PX2uPlSMGYAV 4VG5jaC8=
=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.c om...
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-06-16T22:46:42Z, "Doug Jordan" <dj******@houst on.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)

iD8DBQFA0NS95sR g+Y0CpvERAlGRAK CkUJTaBJIckaWCv M2qkEmA8BDSEgCa Agcp
u44PX2uPlSMGYAV 4VG5jaC8=
=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******@houst on.rr.com> wrote in message
news:51******** *******@fe2.tex as.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.c om...
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

At 2004-06-16T22:46:42Z, "Doug Jordan" <dj******@houst on.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)

iD8DBQFA0NS95sR g+Y0CpvERAlGRAK CkUJTaBJIckaWCv M2qkEmA8BDSEgCa Agcp
u44PX2uPlSMGYAV 4VG5jaC8=
=G3qn
-----END PGP SIGNATURE-----

Jul 18 '05 #4
"Doug Jordan" <dj******@houst on.rr.com> wrote in message news:<m5******* *********@fe2.t exas.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#1 8>", 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*********@zo ran.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**********@m y-deja.com> wrote in message
news:56******** *************** **@posting.goog le.com...
"Doug Jordan" <dj******@houst on.rr.com> wrote in message

news:<m5******* *********@fe2.t exas.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

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

Similar topics

5
3132
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 (count = 0; count <= 1; count++) { if (eval(f.RadioButtons.checked)) { btnChosen = true; }
8
18033
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 <string> #include <iostream> #include <stdarg.h>
8
5462
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 -------------------------------------------------------------------------------- Hello, I have a very simple problem but cannot seem to figure it out. I have a very simple php script that sends a test email to myself. When I debug it in PHP designer, it works with no problems, I get the test email. If
10
4449
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 Enterplise Linux 3 ES, and applied FixPack fp5_mi00069.tar to it. After creating an instance, starting the database, creating a database, and entering the table definitions, all of which seems to work OK, I entered a tiny 8-row table and can do...
2
4571
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 parameter, then it's working fine. Any ideas?? Thanks! public static int getFreq(string s) {... } int res = getFreq({"eee", "ewsww"});
4
9037
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 function ?. My statement is like this CustomOutVal = CustObj.Authenticate(txtUserName.Text, pass , Domain );
45
18847
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 of their elements? Why can't I change the element itself? class Program { private struct MyStruct
10
13644
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 function is also modified. Sometimes I wish to work with "copies", in that when I pass in an integer variable into a function, I want the function to be modifying a COPY, not the reference. Is this possible?
12
3008
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. The global variables and global functions are hidden to prevent from accessing by the programmers. All global functions share global variables. Only very few global functions are allowed to be reusability for the programmers to use. Few...
0
8375
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8815
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8707
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8482
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7306
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6161
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4294
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2714
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1916
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.