Probably a stupid question, but I'm a newbie and this really pisses me
off. Run this script:
import random
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
def Func2():
print output
Func1()
Func2()
And: an error message...... It says:
Traceback (most recent call last):
File "ptls-demo.py", line 11, in ?
Func2()
File "how -the-hell-do-i-fix-this.py", line 8, in Func2
print output
NameError: global name 'output' is not defined
Obviosly, I need to import the variable 'output' from Func1() into
Func2(), but how?
Thanks in advance,
-- /usr/bin/byte 16 1310
Generally, a name defined into a function can't be read outside of it,
so you have to return the function result explicitely:
import random
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
return output
def Func2(item):
print item
output1 = Func1()
Func2(output1)
Bye,
bearophile
Great, thanks
-- /usr/bin/byte
Now what do I do if Func1() has multiple outputs and Func2() requires
them all to give its own output, as follows:
import random
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
output2 = random.choice(choice)
return output
return output2
def Func2(item1, item2):
print item1, item2
output1 = Func1()
Func2(output1)
Thanks in advance,
-- /usr/bin/byte
Byte wrote: Now what do I do if Func1() has multiple outputs and Func2() requires them all to give its own output, as follows:
You can return them as a tuple: def func1():
output1 = 'hi'
output2 = 'bye'
return (output1, output2)
def func2(data):
print data
func2(func1())
('hi', 'bye')
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output return output2
Only the first return statement would run in that code.
Byte wrote: Now what do I do if Func1() has multiple outputs and Func2() requires them all to give its own output, as follows:
import random
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output return output2
The function will return at "return output", so "return output2" will
never be reached.
def Func2(item1, item2): print item1, item2
output1 = Func1() Func2(output1)
Thanks in advance, -- /usr/bin/byte
Try this (I think its called "argument expansion", but I really don't
know what its called, so I can't point you to docs):
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
output2 = random.choice(choice)
return output, output2
def Func2(*items):
print items
output = Func1()
Func2(output1)
BETTER:
=======
You can also make a "generator" (which I have made generalized, which
seems to be what you are striving for):
def Gener1(num):
choice = ('A', 'B', 'C')
for i in xrange(num):
yield random.choice(choice)
def Func2(item):
print item
for item in Gener1(2):
Func2(item)
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
Byte wrote: Now what do I do if Func1() has multiple outputs and Func2() requires them all to give its own output, as follows:
import random
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output return output2
The function will return at "return output", so "return output2" will
never be reached.
def Func2(item1, item2): print item1, item2
output1 = Func1() Func2(output1)
Thanks in advance, -- /usr/bin/byte
Try this (I think its called "argument expansion", but I really don't
know what its called, so I can't point you to docs):
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
output2 = random.choice(choice)
return output, output2
def Func2(*items):
print items
output = Func1()
Func2(*output1)
BETTER:
=======
You can also make a "generator" (which I have made generalized, which
seems to be what you are striving for):
def Gener1(num):
choice = ('A', 'B', 'C')
for i in xrange(num):
yield random.choice(choice)
def Func2(item):
print item
for item in Gener1(2):
Func2(item)
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
James Stroud wrote: Try this (I think its called "argument expansion", but I really don't know what its called, so I can't point you to docs):
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output, output2
def Func2(*items): print items
output = Func1() Func2(*output1)
I was wondering about '*items' when I wrote my response. I left out the
asterisk in my version and it still seems to work. Is it necessary?
John Salerno wrote: James Stroud wrote:
Try this (I think its called "argument expansion", but I really don't know what its called, so I can't point you to docs):
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output, output2
def Func2(*items): print items
output = Func1() Func2(*output1)
I was wondering about '*items' when I wrote my response. I left out the asterisk in my version and it still seems to work. Is it necessary?
Yours is better, after I wrote mine, I realized the asterisk was
unnecessary for this particular example, except that it makes Func2 more
general.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
James Stroud wrote: Yours is better, after I wrote mine, I realized the asterisk was unnecessary for this particular example, except that it makes Func2 more general.
Yeah, I tested it. Func2 prints a tuple of a tuple when the asterisk is
used.
But your generator still wins. :)
John Salerno wrote: James Stroud wrote:
Try this (I think its called "argument expansion", but I really
don't know what its called, so I can't point you to docs):
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output, output2
def Func2(*items): print items
output = Func1() Func2(*output1)
I was wondering about '*items' when I wrote my response. I left out
the asterisk in my version and it still seems to work. Is it necessary?
Yours is better, after I wrote mine, I realized the asterisk was
unnecessary for this particular example, except that it makes Func2
more
general.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095 http://www.jamesstroud.com/
On 17 Mar 2006 12:15:28 -0800
"Byte" <eo********@gmail.com> wrote: Probably a stupid question, but I'm a newbie and this really pisses me off. Run this script:
import random
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice)
def Func2(): print output
Func1() Func2()
Several possible solutions. The simplest (but least
informative):
"""
import random
def Func1():
global output
choice = ('A', 'B', 'C')
output = random.choice(choice)
def Func2():
print output
Func1()
Func2()
"""
i.e. make output a global variable
But as has already been pointed out, you aren't really using
the nature of functions here. Better:
"""
import random
def Func1():
return random.choice(('A', 'B', 'C'))
def Func2(output):
print output
Func2(Func1())
"""
You later ask about returning multiple values. Python is
pretty cool in this respect -- you can return multiple
values in a tuple, which can then be "unpacked"
automatically. This gives you a nice many-to-many idiom for
function calls, e.g.:
x, y = random_point(x_min, x_max, y_min, y_max)
And if you need to pass that to a function which takes two
arguments (x,y), you can:
set_point(*random_point(x_min, x_max, y_min, y_max))
Of course, some people would rather see that expanded out,
and indeed, too many nested function calls can be hard on
the eyes, so you might want to do this anyway:
x, y = random_point(x_min, x_max, y_min, y_max)
set_point(x, y)
or
P = random_point(x_min, x_max, y_min, y_max)
set_point(P)
and of course, it's possible that the function requires the
arguments in a different order, e.g.:
x, y = random_point(1,80,1,25)
set_rowcol(y, x, 'A')
or some such thing.
By far the coolest thing about tuple-unpacking, though, is
that this works like you'd expect it to:
x, y = y, x
instead of being a dumb mistake like this is:
x = y
y = x
which of course should be
temp = y
x = y
y = temp
But ewww that's ugly.
Cheers,
Terry
--
Terry Hancock (ha*****@AnansiSpaceworks.com)
Anansi Spaceworks http://www.AnansiSpaceworks.com
"Byte" <eo********@gmail.com> writes: Probably a stupid question, but I'm a newbie and this really pisses me off. Run this script:
import random
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice)
def Func2(): print output
Func1() Func2()
You could declare output to be global, but it's kind of poor style.
Preferable is something like:
def Func1():
choice = ('A', 'B', 'C')
output = random.choice(choice)
return output
def Func2(x):
print x
output = Func1() # this "output" is not the same as the one in Func1
Func2(output)
James Stroud wrote: Try this (I think its called "argument expansion", but I really don't know what its called, so I can't point you to docs):
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output, output2
def Func2(*items): print items
output = Func1() Func2(*output1)
Single asterisk == "arbitrary argument list". Useful in certain
patterns, but not something you use every day.
Documentation is in the tutorial: http://www.python.org/doc/current/tu...00000000000000
PS: Like "self" for class instance methods, "*args" is the
conventional name of the arbitrary argument list.
--Ben
"Try this (I think its called "argument expansion", but I really don't
know what its called, so I can't point you to docs):"
This works, thanks. But how acn I get rid of the ugly surrounding
brackets and commas?
e.g. If the scripts overall output was (('B', 'C'),), how to change it
to just B C?
Byte wrote: "Try this (I think its called "argument expansion", but I really don't know what its called, so I can't point you to docs):"
This works, thanks. But how acn I get rid of the ugly surrounding brackets and commas?
e.g. If the scripts overall output was (('B', 'C'),), how to change it to just B C?
You can get rid of the outer parentheses by removing the asterisk from
the parameter list. But the other parentheses: ('B', 'C') will remain,
because it's a tuple. You can access the values by indexing.
Byte wrote: Now what do I do if Func1() has multiple outputs and Func2() requires them all to give its own output, as follows:
import random
def Func1(): choice = ('A', 'B', 'C') output = random.choice(choice) output2 = random.choice(choice) return output return output2
def Func2(item1, item2): print item1, item2
output1 = Func1() Func2(output1)
Some more options (untested):
def func1(n, choice=('A', 'B', 'C')):
# n=number of choices
# choice can now be overridden with
# other values
choices = []
for i in range(n):
choices.append(random.choice(choice))
return choices
def func2(choices):
for choice in choices:
print choice,
print
func2(func1(2))
#########################################
class ChoosePrinter(object):
def __init__(self, to_choose_from=('A', 'B', 'C')):
self.to_choose_from=to_choose_from
self.choosen = []
def get_choices(self, n=2):
for i in range(n):
self.choosen.append(random.choice(choice))
def dump_choosen(self):
print " ".join(self.choosen)
self.choosen = []
cp = ChoosePrinter()
cp.get_choices(2)
cp.dump_choosen() This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Jeff Wagner |
last post by:
I am importing a file which contains a persons name (firstName, middleName, etc). If I define a
function to do this, how can I use the variables outside of that function?
Here is the code:
...
|
by: J. Kenney |
last post by:
Good Morning,
Is there a way for a function called within an _imported_
library to call back to _calling_ python program to run a
function? (Shown below)
Also can you overload the print...
|
by: Kamilche |
last post by:
I have a large project that is getting complex, and I would like to
print the docstrings without importing the modules. The only Python
utility I could find references is apparently defunct and...
|
by: steve |
last post by:
Hello,
I am trying to import an image file into a form. This would be a
persons picture saved in the same directory for every unique record.
I don't have any problems making an action button to...
|
by: Tony Williams |
last post by:
Is it possible to import a spreadsheet from Excel where the rows contain the
field names rather than the columns? I'm creating an Excel spreadsheet but
there are over 50 items to import and would...
|
by: Natan |
last post by:
When you create and aspx page, this is generated by default:
using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Text;
using...
|
by: hharriel |
last post by:
Hi,
I am hoping someone can help me with an issue I am having with excel
and ms access. I have collected data (which are in individual excel
files) from 49 different school districts. All...
|
by: JMO |
last post by:
I can import a csv file with no problem. I can also add columns to the
datagrid upon import. I want to be able to start importing at the 3rd
row. This will pick up the headers necessary for the...
|
by: rs387 |
last post by:
Hi,
I've found the following behaviour on importing a variable from a
module somewhat odd. The behaviour is identical in Python 2.5 and
3.0b2.
In summary, here's what happens. I have a...
|
by: DolphinDB |
last post by:
Tired of spending countless mintues downsampling your data? Look no further!
In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
|
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...
|
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...
|
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)...
|
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...
|
by: Defcon1945 |
last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
|
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....
|
by: af34tf |
last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
|
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...
| |