Importing from a file to use contained variables
Anthony Borla
ajborla at bigpond.com
Sat Nov 29 00:39:32 EST 2003
"Jeff Wagner" <JWagner at hotmail.com> wrote in message
news:ks4gsvkgs50a2ic9e7a48jf0hcufer42r7 at 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
More information about the Python-list
mailing list