I’m about 500 lines of code into my Python project, and I am having a blast. Finally, I’ve begun to apply the knowledge gained from reading countless Python tomes. I used to wonder how people cranked out 1000’s of lines of code. I don’t anymore. It’s surprisingly easy to write a lot of code in a short time. I probably need to come up with a better way of testing/debugging than running whole sections of code over and over just to see if the last changes will crash the program.
What I enjoy especially has been writing some code, and then going back and improving it, e.g. by creating and calling functions rather than writing repetitive sections of code. I guess you could call that refactoring.
An exaple (taken from my project) follows. To get data into my program, I’ve been writing things like this – method that’s part of class to be instantiated every time a project object is created (for more context see recent posts):
self.Title = raw_input(“Enter Project Title Line 1: “)
self.Title2 = raw_input(“Enter Project Title Line 2: “)
self.Name = raw_input(“Enter Project Title Line 3: “)
self.Location = raw_input(“Enter Project Location Line 1: “)
and on and on… pretty redundant code, huh ? Plus, I was wondering how to add some validation to my inputs, e.g. data type, values etc. So I came up with this funtion to be called instead of raw_input every time I prompt the user for data entry.
def dataEntry(item, prompt, checktype, choices):
while count == 0:
question = “Enter “+ item+ “: <“+ prompt +”> ”
data = raw_input(question)
if type(data) == checktype:
# print “correct type”
if data.upper() in choices:
# print “condition true”
print “Select from: “,
for each in choices:
if each != choices[len(choices)-1]:
print each, “or“,
A simple example of how this would work is:
Entry = dataEntry(“Title“,”Investigation“, types.StringType, [“Investigation“,”Evaluation“,”Examination“])
You are prompted:
Enter Title: <Investigation>
You can enter your own string, which has to be one of the three in choices, or accept the default by just hitting <Enter>. I put the check for datatype in because I will be using this for a wide range of data entry that will include numeric and string data, and I need data to be re-entered if it’s the wrong kind. Essentially, instead of just collecting data with raw_input and then running checks, the check parameters are fed to the function and all the checking “happens in the function definition.
I hope what I tried to accomplish here is more or less self-explanatory. Please – I’m a beginner – let me know how I can make this even better or more Pythonic.
PS (07/15/2010): My type checking, of course, is hampered by the fact that anything entered thru raw_input is string. Obviously, this needs some refining.