My first foray into python

This project had a lot of firsts for me. First time contributing to open source, first time with git, and first time using python.

Along with learning the very basics of python, I was able to expand on PyRunner’s use of the configparser. With it you can quickly create and access sections and variables in a text file.

#If the section does not exist, create it.
config = ConfigParser.ConfigParser()
config.readfp(open('pyRunner.cfg'))
if not ( config.has_section(score_type) ):
# Creating the needed section.
config.add_section(score_type)
config.set(score_type,"1", "0")
config.set(score_type,"2", "0")
...
config.set(score_type,"10", "0")
with open('pyRunner.cfg', 'wb') as configfile:
config.write(configfile)

As you can see, there are convenient functions built in that let you, for example, check for the existence of a section in your file.

And here is what the config file that is generated (and updated in this case) looks like.

[endurance]
10 = 0
1 = 202
3 = 0
2 = 0

The other piece I expanded on was the score keeping system. We wanted to have a top 10 list rather than just the single top score. Here is some recursion I used to do it.

for i in range(1, 11):
if ( int(score) > int(config.get(score_type, str(i))) ):
#store the value I am about to replace
replaced_score = config.get(score_type, str(i))
#replace the value in the list
config.set(score_type, str(i), str(int(score)))
with open('pyRunner.cfg', 'wb') as configfile:
config.write(configfile)
#find the replaced score's new place in the list
ranking(replaced_score)
#immediatly end the loop when the recursion unwinds
break

Yes it is simple. But I did learn what happens in python when a recursive function gets away from you. Initially, I forgot to type cast the score variable above leading to this…
RuntimeError: maximum recursion depth exceeded while calling a Python object
Rather than forcing you to kill the process manually, python does it for you and lets you know that it did. Nice.
–Dennis

Advertisements

Post your comments

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s