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:
import string
def getName():
data = open("enterName.txt")
allNames = data.readlines()
data.close()
fName = string.lower(allNames[0])
mName = string.lower(allNames[1])
lName = string.lower(allNames[2])
nName = string.lower(allNames[3])
pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers.
Since these are local to the function, how is this done? Can I make them global or something?
Thanks, Jeff 11 2085
"Jeff Wagner" <JW*****@hotmail.com> wrote in message
news:ks********************************@4ax.com... 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?
You can simply return data from a function. Examples:
def returnString():
return "ABCDE"
def returnInteger():
return 5 + 5
def returnList():
return ['a', 'B', 1, 3, 5] Here is the code:
import string
def getName():
data = open("enterName.txt") allNames = data.readlines() data.close()
fName = string.lower(allNames[0]) mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers.
Since these are local to the function, how is this done? Can I make them global or something?
Global data is, probably, best avoided [this is a general program design
principle, not something specific to Python]. As shown in the earlier code,
you can return any data type, so, why not return data in the most convenient
form, the one that best suits your purposes ?
You now have enough enough information to design a solution. May I simply
suggest, however, that you distinguish between a single entity, and a group
of entities. By this I mean you would write function(s) to manipulate the
data belonging to a single entity [the names of a person], and function(s)
to manipulate groups of persons [you will probably want to, later on, store
multiple persons in a file].
I hope this helps.
Anthony Borla
On Sat, 29 Nov 2003 05:39:32 GMT, "Anthony Borla" <aj*****@bigpond.com> wrotf: "Jeff Wagner" <JW*****@hotmail.com> wrote in message news:ks********************************@4ax.com.. . 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?
You can simply return data from a function. Examples:
def returnString(): return "ABCDE"
def returnInteger(): return 5 + 5
def returnList(): return ['a', 'B', 1, 3, 5]
Here is the code:
import string
def getName():
data = open("enterName.txt") allNames = data.readlines() data.close()
fName = string.lower(allNames[0]) mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers.
Since these are local to the function, how is this done? Can I make them global or something?
Global data is, probably, best avoided [this is a general program design principle, not something specific to Python]. As shown in the earlier code, you can return any data type, so, why not return data in the most convenient form, the one that best suits your purposes ?
You now have enough enough information to design a solution. May I simply suggest, however, that you distinguish between a single entity, and a group of entities. By this I mean you would write function(s) to manipulate the data belonging to a single entity [the names of a person], and function(s) to manipulate groups of persons [you will probably want to, later on, store multiple persons in a file].
I hope this helps.
Anthony Borla
Here's the solution I came up with (maybe not the best?):
def getName():
data = open("enterName.txt")
allNames = data.readlines()
data.close()
fName = string.lower(allNames[0])
mName = string.lower(allNames[1])
lName = string.lower(allNames[2])
nName = string.lower(allNames[3])
pName = string.lower(allNames[4])
fullName = fName, mName, lName, nName, pName
return fullName
nameList = getName()
Then when I need nameList in another module, I used:
from GetName import nameList
and went from there. Whew, there sure is a lot to learn. I thought I was understanding it pretty
well when I was reading some books and tutorials but when I started to write code, I seemed to
forget everything.
Now I'm trying to figure out how to process this list (which I think is really a string) and get the
numerical value for each name.
This is my string:
('Jeffery', 'Thomas', 'Wagner', 'Jeff', 'Wagner')
and I have to take each name and add up what each letter represents.
Here's what I have so far:
for eachName in nameList:
print eachName #just to let me see that each name is correct .. I will remove it later
for eachName[len(eachName)-1]
call my masterNumber routine to add them all together
and I'm totally stuck. I have to add up J+E+F+F+E+R+Y and send it to the masterNumber routine to get
a total.
For some reason, when I got the length of eachName, it was giving me one value over the correct
answer and hence, I subtracted one.
This is challenging to say the least but fun, too.
Jeff
I think I just figured out part of my problem.
I have to change the line:
fullName = fName, mName, lName, nName, pName
to
fullName = fName[:-1], mName[:-1], lName[:-1], nName[:-1], pName
to remove the trailing "\n"
This gives me part of my solution ;)
Jeff Here's the solution I came up with (maybe not the best?):
def getName():
data = open("enterName.txt") allNames = data.readlines() data.close() fName = string.lower(allNames[0]) mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4]) fullName = fName, mName, lName, nName, pName return fullName
nameList = getName()
Then when I need nameList in another module, I used:
from GetName import nameList
and went from there. Whew, there sure is a lot to learn. I thought I was understanding it pretty well when I was reading some books and tutorials but when I started to write code, I seemed to forget everything.
Now I'm trying to figure out how to process this list (which I think is really a string) and get the numerical value for each name.
This is my string:
('Jeffery', 'Thomas', 'Wagner', 'Jeff', 'Wagner')
and I have to take each name and add up what each letter represents.
Here's what I have so far:
for eachName in nameList: print eachName #just to let me see that each name is correct .. I will remove it later for eachName[len(eachName)-1] call my masterNumber routine to add them all together
and I'm totally stuck. I have to add up J+E+F+F+E+R+Y and send it to the masterNumber routine to get a total.
For some reason, when I got the length of eachName, it was giving me one value over the correct answer and hence, I subtracted one.
This is challenging to say the least but fun, too.
Jeff
Jeff Wagner <JW*****@hotmail.com> wrote: 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:
import string
def getName():
data = open("enterName.txt") allNames = data.readlines() data.close()
fName = string.lower(allNames[0]) mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers. Since these are local to the function, how is this done? Can I make them global or something?
class getName:
def __init__(self, filename):
(
self.fName, self.mName, self.lName, self.nName, self.pName
) = [k.lower() for k in file(filename).readlines()]
names = getName("enterName.txt")
print names.fName
print names.mName
print names.lName
--
- Tim Roberts, ti**@probo.com
Providenza & Boekelheide, Inc.
On Fri, 28 Nov 2003 22:49:07 -0800, Tim Roberts <ti**@probo.com> wrotf: Jeff Wagner <JW*****@hotmail.com> wrote: 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:
import string
def getName():
data = open("enterName.txt") allNames = data.readlines() data.close()
fName = string.lower(allNames[0]) mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers. Since these are local to the function, how is this done? Can I make them global or something?
class getName: def __init__(self, filename): ( self.fName, self.mName, self.lName, self.nName, self.pName ) = [k.lower() for k in file(filename).readlines()]
names = getName("enterName.txt")
print names.fName print names.mName print names.lName
Sweeeeeeet! I haven't gotten to classes yet ... I guess I just did ;)
Thanks a lot,
Jeff
Jeff Wagner fed this fish to the penguins on Friday 28 November 2003
22:05 pm: Here's the solution I came up with (maybe not the best?):
def getName():
data = open("enterName.txt") allNames = data.readlines() data.close() fName = string.lower(allNames[0]) mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4]) fullName = fName, mName, lName, nName, pName return fullName
nameList = getName()
Then when I need nameList in another module, I used:
from GetName import nameList
This will only let you handle ONE set of data, since you are
referencing just the results of one call to getName()...
and went from there. Whew, there sure is a lot to learn. I thought I was understanding it pretty well when I was reading some books and tutorials but when I started to write code, I seemed to forget everything.
Looks a bit like you are trying to modularize the task before even
getting the logic of how to pass data into and out of functions.
Now I'm trying to figure out how to process this list (which I think is really a string) and get the numerical value for each name.
Ah... numeralogy <G> Ignoring your "master numbers" special cases, I
presume that A=1, B=2... Z=26?, and that the output range is 0..9
Try hacking the following three files (watch out for line wraps):
-=-=-=-=-=- main.py
#
# main application file for numeralogy exercise
#
import Person
import Number
import sys
if len(sys.argv) > 1:
data = file(sys.argv[1], "r")
else:
data = None
while 1:
p = Person.Person(data)
if not p.Valid: break
print p.fName, Number.reduction(Number.encode(p.fName))
print p.mName, Number.reduction(Number.encode(p.mName))
print p.lName, Number.reduction(Number.encode(p.lName))
print p.nName, Number.reduction(Number.encode(p.nName))
print p.pName, Number.reduction(Number.encode(p.pName))
if data: data.close()
-=-=-=-=-=- Person.py
#
# Person class file
#
class Person:
def __init__(self, fid = None):
if fid:
self.fName = fid.readline().strip()
self.mName = fid.readline().strip()
self.lName = fid.readline().strip()
self.nName = fid.readline().strip()
self.pName = fid.readline().strip()
self.Valid = ( self.fName
and self.mName
and self.lName
and self.nName
and self.pName )
else:
try:
self.fName = raw_input("Enter first name: ").strip()
self.mName = raw_input("Enter middle name: ").strip()
self.lName = raw_input("Enter last name: ").strip()
self.nName = raw_input("Enter nick name: ").strip()
self.pName = raw_input("Enter preferred name: ").strip()
self.Valid = ( self.fName
and self.mName
and self.lName
and self.nName
and self.pName )
except:
self.Valid = 0
-=-=-=-=- Number.py
#
# number cruncher file
#
def encode(aName):
aName = aName.lower()
sum = 0
for ch in aName:
sum += (ord(ch) - ord("a") + 1)
return sum
def reduction(aNumber):
# ignores special values, just reduces to range 0..9
# recursive definition
if aNumber > 9:
sum = 0
for ch in str(aNumber):
sum += int(ch)
return reduction(sum)
else:
return aNumber
The main routine will, if supplied on the command line, open the data
file. Person.Person() will, if given an open file reference, read the
next five lines from the file, otherwise it will prompt the console for
the names. An empty name causes the "valid" flag to go false, which
breaks the loop in the main file.
Number.encode() takes a name, converts each character into a number
from 1..26, and sums them. Number.reduction() (reduce is already a
Python operation) takes an integer, if it is in the 0..9 range returns
it, otherwise takes the string representation of it (easier to get to
each digit as a character), then adds the individual digits, before
calling itself recursively on the new value.
Shouldn't be too difficult to insert an if block for your special case
values.
-- ================================================== ============ < wl*****@ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < wu******@dm.net | Bestiaria Support Staff < ================================================== ============ < Bestiaria Home Page: http://www.beastie.dm.net/ < Home Page: http://www.dm.net/~wulfraed/ <
On Sat, 29 Nov 2003 03:39:34 GMT, Jeff Wagner <JW*****@hotmail.com> wrote: 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?
Does the file only contain ONE person's info, or does the pattern of 5 lines repeat for more?
If it's only one person, as you have it here, you can just split on line endings, like
def getName(): return map(str.lower, file('enterName.txt').read().splitlines())
to return a list of the lower case strings you want, which you can then do
an unpacking assignment with, e.g.,
fName, mName, lName, nName, pName = getName()
But that's sure a special-purpose routine, being locked into just using the first five lines
of a particular file with a fixed file name.
If you have other possible files of the same format, and possibly with more than one
person's info (i.e., repeating groups of 5 lines), I'd suggest a generator that you
can pass a file name to, and which will return the info in successive lists of 5.
E.g., the following looks like a function, but the 'yield' makes it a generator-maker
====< JeffWagner.py >====================================
def mkgen_GetName(fileOrPath):
if isinstance(fileOrPath, str):
fileOrPath = file(fileOrPath) # use open file or open by name
lineCount = 0
for line in fileOrPath:
if lineCount%5==0: nameList = []
nameList.append(line.strip().lower()) # strips white space incl newline if any
lineCount += 1
if lineCount%5==0: yield nameList
def test():
from StringIO import StringIO
siofile = StringIO("""\
John
Q
Public
JQ
Johnny
Alice
B
Choklas
Allie
Chok
""")
for fName, mName, lName, nName, pName in mkgen_GetName(siofile):
# do whatever with each successive person-info set ...
print ('%10s'*5)%(fName, mName, lName, nName, pName)
if __name__ == '__main__':
test()
================================================== =======
if you run this, you get:
[13:00] C:\pywk\clp>jeffwagner.py
john q public jq johnny
alice b choklas allie chok
It also has the advantage that it doesn't put the whole file in memory, just what it needs
as it goes. Here is the code:
import string
Are you still using 1.5.2? You really ought to upgrade to 2.3.2 ;-) def getName():
data = open("enterName.txt")
^^^^ ^^^^^^^^^^^^^-- do you really want this as a fixed name in your function?
|
+-- deprecated in favor of 'file'
allNames = data.readlines()
^^^^^^^^^^^-- reads the whole file into memory. Not so good for big files. data.close()
^^^^^^^^^^^^ good practice, but not necessary if you are using cPython. fName = string.lower(allNames[0])
fName = allNames[0].lower() # current way to spell previous line
# (hence importing string is not necessary)
mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers. Since these are local to the function, how is this done? Can I make them global or something?
'or something' is preferred ;-)
BTW, if you don't want to use a loop to sequence through the data, you can get it one set
at a time from the generator's .next method, e.g., from JeffWagner import mkgen_GetName if 1: # so I can copy/paste from the source file
... from StringIO import StringIO
... siofile = StringIO("""\
... John
... Q
... Public
... JQ
... Johnny
... Alice
... B
... Choklas
... Allie
... Chok
... """)
... gen = mkgen_GetName(siofile) gen.next()
['john', 'q', 'public', 'jq', 'johnny'] a,b,c,d,e = gen.next() a,b,c
('alice', 'b', 'choklas') d,e
('allie', 'chok') gen.next() # expecting the StopIteration exception here
Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration # so you will have to catch that to use .next() cleanly
BTW, what does pName stand for?
Regards,
Bengt Richter
On 29 Nov 2003 21:04:25 GMT, bo**@oz.net (Bengt Richter) wrotf: On Sat, 29 Nov 2003 03:39:34 GMT, Jeff Wagner <JW*****@hotmail.com> wrote:
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?Does the file only contain ONE person's info, or does the pattern of 5 lines repeat for more?
It contains only one person's info at a time.
If it's only one person, as you have it here, you can just split on line endings, like
def getName(): return map(str.lower, file('enterName.txt').read().splitlines())
to return a list of the lower case strings you want, which you can then do an unpacking assignment with, e.g.,
fName, mName, lName, nName, pName = getName()
Excellent, I'll play around with this.
But that's sure a special-purpose routine, being locked into just using the first five lines of a particular file with a fixed file name.
If you have other possible files of the same format, and possibly with more than one person's info (i.e., repeating groups of 5 lines), I'd suggest a generator that you can pass a file name to, and which will return the info in successive lists of 5.
E.g., the following looks like a function, but the 'yield' makes it a generator-maker
What is a generator maker?
====< JeffWagner.py >==================================== def mkgen_GetName(fileOrPath): if isinstance(fileOrPath, str): fileOrPath = file(fileOrPath) # use open file or open by name lineCount = 0 for line in fileOrPath: if lineCount%5==0: nameList = [] nameList.append(line.strip().lower()) # strips white space incl newline if any lineCount += 1 if lineCount%5==0: yield nameList
def test(): from StringIO import StringIO siofile = StringIO("""\ John Q Public JQ Johnny Alice B Choklas Allie Chok """) for fName, mName, lName, nName, pName in mkgen_GetName(siofile): # do whatever with each successive person-info set ... print ('%10s'*5)%(fName, mName, lName, nName, pName)
if __name__ == '__main__': test() ================================================= ========
if you run this, you get:
[13:00] C:\pywk\clp>jeffwagner.py john q public jq johnny alice b choklas allie chok
It also has the advantage that it doesn't put the whole file in memory, just what it needs as it goes.
Here is the code:
import string
Are you still using 1.5.2? You really ought to upgrade to 2.3.2 ;-)
def getName():
data = open("enterName.txt")
^^^^ ^^^^^^^^^^^^^-- do you really want this as a fixed name in your function? | +-- deprecated in favor of 'file'
allNames = data.readlines() ^^^^^^^^^^^-- reads the whole file into memory. Not so good for big files. data.close() ^^^^^^^^^^^^ good practice, but not necessary if you are using cPython. fName = string.lower(allNames[0])
fName = allNames[0].lower() # current way to spell previous line # (hence importing string is not necessary)
mName = string.lower(allNames[1]) lName = string.lower(allNames[2]) nName = string.lower(allNames[3]) pName = string.lower(allNames[4])
I need to use these variables in another function (routine) to calculate the associated numbers. Since these are local to the function, how is this done? Can I make them global or something? 'or something' is preferred ;-)
BTW, if you don't want to use a loop to sequence through the data, you can get it one set at a time from the generator's .next method, e.g.,
from JeffWagner import mkgen_GetName if 1: # so I can copy/paste from the source file ... from StringIO import StringIO ... siofile = StringIO("""\ ... John ... Q ... Public ... JQ ... Johnny ... Alice ... B ... Choklas ... Allie ... Chok ... """) ... gen = mkgen_GetName(siofile) gen.next() ['john', 'q', 'public', 'jq', 'johnny'] a,b,c,d,e = gen.next() a,b,c ('alice', 'b', 'choklas') d,e ('allie', 'chok') gen.next() # expecting the StopIteration exception here Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration # so you will have to catch that to use .next() cleanly
BTW, what does pName stand for?
Regards, Bengt Richter
>====< JeffWagner.py >==================================== def mkgen_GetName(fileOrPath): if isinstance(fileOrPath, str): fileOrPath = file(fileOrPath) # use open file or open by name lineCount = 0 for line in fileOrPath: if lineCount%5==0: nameList = [] nameList.append(line.strip().lower()) # strips white space incl newline if any lineCount += 1 if lineCount%5==0: yield nameList
def test(): from StringIO import StringIO siofile = StringIO("""\ John Q Public JQ Johnny Alice B Choklas Allie Chok """) for fName, mName, lName, nName, pName in mkgen_GetName(siofile): # do whatever with each successive person-info set ... print ('%10s'*5)%(fName, mName, lName, nName, pName)
if __name__ == '__main__': test() ================================================= ========
if you run this, you get:
[13:00] C:\pywk\clp>jeffwagner.py john q public jq johnny alice b choklas allie chok
It also has the advantage that it doesn't put the whole file in memory, just what it needs as it goes.
Here is the code:
import stringAre you still using 1.5.2? You really ought to upgrade to 2.3.2 ;-)
I am using 2.3.2. def getName():
data = open("enterName.txt") ^^^^ ^^^^^^^^^^^^^-- do you really want this as a fixed name in your function? | +-- deprecated in favor of 'file'
allNames = data.readlines() ^^^^^^^^^^^-- reads the whole file into memory. Not so good for big files. data.close() ^^^^^^^^^^^^ good practice, but not necessary if you are using cPython.
You mean that it closes itself by default?
BTW, if you don't want to use a loop to sequence through the data, you can get it one set at a time from the generator's .next method, e.g.,
from JeffWagner import mkgen_GetName if 1: # so I can copy/paste from the source file ... from StringIO import StringIO ... siofile = StringIO("""\ ... John ... Q ... Public ... JQ ... Johnny ... Alice ... B ... Choklas ... Allie ... Chok ... """) ... gen = mkgen_GetName(siofile) gen.next() ['john', 'q', 'public', 'jq', 'johnny'] a,b,c,d,e = gen.next() a,b,c ('alice', 'b', 'choklas') d,e ('allie', 'chok') gen.next() # expecting the StopIteration exception here Traceback (most recent call last): File "<stdin>", line 1, in ? StopIteration # so you will have to catch that to use .next() cleanly
Thanks, I'll have to play around with these ideas. I'm still very much a beginner.
BTW, what does pName stand for?
pName stands for Present Name ... mostly used for women who have taken on their husbands last name.
In numerology, the name one was born with is most important but nickNames and any other change of
name (married name) is taken into account, also.
Thanks, Jeff
Regards, Bengt Richter
> Ah... numeralogy <G> Ignoring your "master numbers" special cases, I presume that A=1, B=2... Z=26?, and that the output range is 0..9
That is what's known as "modern" numerology and sometimes (incorrectly) called Pythagorean
numerology (Pythagoras had nothing to do with it). I use a system called Chaldean numerology which
is more ancient. It assigns numeric values to each letter according to it's "vibration" or sound.
This is similar to the Hebrew alphabet where each letter has a numeric equivalent ... not just A-Z
and 1-9 repeatedly.
When I first wrote this program in VB, I gave a choice of using either system so I could compare the
results. Using the modern method, the results weren't even close; using the Chaldean system just
blew people away when the read their charts.
I'm not as much into numerology anymore but it is interesting if done right ... like astrology,
numerology can be a game or an interesting study in mysticism.
Try hacking the following three files (watch out for line wraps):
I will, thanks!
Jeff
-=-=-=-=-=- main.py # # main application file for numeralogy exercise #
import Person import Number
import sys
if len(sys.argv) > 1: data = file(sys.argv[1], "r") else: data = None
while 1: p = Person.Person(data)
if not p.Valid: break
print p.fName, Number.reduction(Number.encode(p.fName)) print p.mName, Number.reduction(Number.encode(p.mName)) print p.lName, Number.reduction(Number.encode(p.lName)) print p.nName, Number.reduction(Number.encode(p.nName)) print p.pName, Number.reduction(Number.encode(p.pName))
if data: data.close()
-=-=-=-=-=- Person.py # # Person class file #
class Person: def __init__(self, fid = None): if fid: self.fName = fid.readline().strip() self.mName = fid.readline().strip() self.lName = fid.readline().strip() self.nName = fid.readline().strip() self.pName = fid.readline().strip() self.Valid = ( self.fName and self.mName and self.lName and self.nName and self.pName ) else: try: self.fName = raw_input("Enter first name: ").strip() self.mName = raw_input("Enter middle name: ").strip() self.lName = raw_input("Enter last name: ").strip() self.nName = raw_input("Enter nick name: ").strip() self.pName = raw_input("Enter preferred name: ").strip() self.Valid = ( self.fName and self.mName and self.lName and self.nName and self.pName ) except: self.Valid = 0
-=-=-=-=- Number.py # # number cruncher file #
def encode(aName): aName = aName.lower() sum = 0 for ch in aName: sum += (ord(ch) - ord("a") + 1) return sum
def reduction(aNumber): # ignores special values, just reduces to range 0..9 # recursive definition if aNumber > 9: sum = 0 for ch in str(aNumber): sum += int(ch) return reduction(sum) else: return aNumber The main routine will, if supplied on the command line, open the data file. Person.Person() will, if given an open file reference, read the next five lines from the file, otherwise it will prompt the console for the names. An empty name causes the "valid" flag to go false, which breaks the loop in the main file.
Number.encode() takes a name, converts each character into a number from 1..26, and sums them. Number.reduction() (reduce is already a Python operation) takes an integer, if it is in the 0..9 range returns it, otherwise takes the string representation of it (easier to get to each digit as a character), then adds the individual digits, before calling itself recursively on the new value.
Shouldn't be too difficult to insert an if block for your special case values.
Jeff Wagner wrote in message ... On 29 Nov 2003 21:04:25 GMT, bo**@oz.net (Bengt Richter) wrotf:
What is a generator maker?
My advice is not to play around with this until you get the basics down,
because generators and generator functions embody a number of very advanced
concepts.
I make it sound scary, but really all it is is this:
def count(): #Defines a generator factory.
n = 0
while n < 10:
yield n
n += 1
mycounter = count() #Gets a generator instance from the factory.
mycounter.next() # returns 0.
for i in mycounter: print i, # prints "1 2 3 4 5 6 7 8 9"
Generators are a strange mix of functions and classes: using the 'next'
method of a generator, execution advances to the next "yield" statement,
where it then "returns" whatever's to the right of the 'yield'. When the
generator hits a real or implied 'return', it raises a StopIteration
exception, and stops for good.
The 'for' statement and other things like list() all use these next() and
StopIteration things implicitly. This behavior is part of the "generator
protocol", and anything that implements it can be used as a generator.
Generators are nifty because they are very fast, use very few resources, and
can make many complex state-related problems easier to code. They're
relatively new to Python--few languages have anything like them at all.
They're not a must-have, but they are very useful.
Now stay away from them until you know what you're doing. ;)
--
Francis Avila This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Vsevolod (Simon) Ilyushchenko |
last post by:
Hi,
Last year I have written a Perl module to serve as a backend to
Macromedia Flash applications: http://www.simonf.com/amfperl
I have just rewritten it in Python, which I have not used...
|
by: Mark English |
last post by:
Basic problem:
If there is a C-extension module in a package and it tries to import
another python module in the same package without using the fully
qualified path, the import fails.
Config:...
|
by: Steve George |
last post by:
Hi, I have a scenario where I have a master schema that defines a
number of complex and simple types. I then have a number of other
schemas (with different namespaces) where I would like to reuse...
|
by: D Mat |
last post by:
Hi,
I'm trying to get MS Access 2000 to automatically import a series of
(~200) flat text, tab delimited, data files into a single Access table,
with consistent fields and rows.
The files have...
|
by: Sam Lazarus |
last post by:
I need to import data from a website, but the text is arranged badly:
Name:John Doe
Title:Grunt
ID:314159
Name:Jane Doe
Title:Queen-Bee
ID:271828
etc...
|
by: Ali |
last post by:
I am having problem compiling schema contained in WSDL file when analyzing
schema types contained in it (for example
http://www.ebout.net/net/GoogleSearch.wsdl).
Following code demonstrates my...
|
by: Snozz |
last post by:
The short of it:
If you needed to import a CSV file of a certain structure on a regular
basis(say 32 csv files, each to one a table in 32 databases), what
would be your first instinct on how to...
|
by: kkadakia |
last post by:
I get a daily excel file for a entire month which I want to transfer into Access at the end of the month. So, there are around 20-25 excel files I get by the end of the month, and I would like to...
|
by: rshepard |
last post by:
I'm stymied by what should be a simple Python task: accessing the value of
a variable assigned in one module from within a second module. I wonder if
someone here can help clarify my thinking. I've...
|
by: Kemmylinns12 |
last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and efficiency. While initially associated with cryptocurrencies...
|
by: Naresh1 |
last post by:
What is WebLogic Admin Training?
WebLogic Admin Training is a specialized program designed to equip individuals with the skills and knowledge required to effectively administer and manage Oracle...
|
by: Matthew3360 |
last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function.
Here is my code.
header("Location:".$urlback);
Is this the right layout the...
|
by: Matthew3360 |
last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it so the python app could use a http request to get...
|
by: Arjunsri |
last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and credentials and received a successful connection...
|
by: Matthew3360 |
last post by:
Hi,
I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web server and have made sure to enable curl. I get a...
|
by: Carina712 |
last post by:
Setting background colors for Excel documents can help to improve the visual appeal of the document and make it easier to read and understand. Background colors can be used to highlight important...
|
by: BLUEPANDA |
last post by:
At BluePanda Dev, we're passionate about building high-quality software and sharing our knowledge with the community. That's why we've created a SaaS starter kit that's not only easy to use but also...
|
by: Ricardo de Mila |
last post by:
Dear people, good afternoon...
I have a form in msAccess with lots of controls and a specific routine must be triggered if the mouse_down event happens in any control.
Than I need to discover what...
| |