By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,795 Members | 1,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,795 IT Pros & Developers. It's quick & easy.

Importing from a file to use contained variables

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
11 Replies


P: n/a

"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
Jul 18 '05 #2

P: n/a
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
Jul 18 '05 #3

P: n/a
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


Jul 18 '05 #4

P: n/a
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.
Jul 18 '05 #5

P: n/a
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
Jul 18 '05 #6

P: n/a
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/ <


Jul 18 '05 #7

P: n/a
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
Jul 18 '05 #8

P: n/a
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


Jul 18 '05 #9

P: n/a
>====< 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


Jul 18 '05 #10

P: n/a
> 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.


Jul 18 '05 #11

P: n/a
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

Jul 18 '05 #12

This discussion thread is closed

Replies have been disabled for this discussion.