Python Scripting

Hello everybody!

We were introduced to Python this week. If I had to recommend a programming language that all programmers should know in addition to a high level language such as C++/Java, it would be either Python or Perl because of the importance of scripting in the programming world today. I worked for Cadence Design Systems two summers ago and I actually gained some experience working with TCL which is a primitive scripting language so I think it’s comparatively easier for me to understand the advantages of a much more advanced and higher-level scripting language.

During my internship at Qualcomm this past summer, I encountered a problem that would have been easily resolved with a scripting language such as Python. Without getting into too much technical detail, I was working on a lot of low-level C and assembly files for the major portion of my internship. With regard to the assembly files, I was working on an ISA that specifically provided details on each assembly instruction of a particular processor and I was adding additional information to the assembly file instruction by instruction looking at specific bits of each instruction. Python would have been a great tool to use in retrospect because I could have automated the process to a large extent.

I’m definitely looking forward to learning more about Python and becoming somewhat proficient at the end of the class.

Until next time!

Final Project: The Walking Dead Text-based Adventure Game

So for our Intro to Unix final project, 3 other guys and I created a text-based adventure game based on the popular AMC TV series The Walking Dead. It was writting using Python and an expandable structure so that it can easily be added on to. It actually turned out really great; we’re all definitely proud of how it turned out. We accomplished every goal we set out to achieve in the beginning when we first met up.

Here’s the link to the GitHub repository where you can download a zip file and follow the README for starting the game:

https://github.com/cas26547/WalkingDeadGame/tree/master/WalkingDead

If you have any feedback feel free to comment below!

Final Project Near Completion

Our final project has reached completion. Everything works, the only thing left to do is to play the game for hours on end and try to produce errors, as well as catch spelling mistakes and proper spacing. Since the last post, a great deal of thought went into considering the fighting style of the game. We ended up implementing a Pokémon style, where you take turns with the zombie hitting each other. The player has a plethora of weapons that are obtained thought their navigation of the game. Ammo will be limited and an infinite use knife will be provided at the beginning of the game. The fights also have random components like weapon accuracy and chance of running into a zombie.

It is also worth mentioning the save and load game functions. They both extensively used python’s pickle module. It is used for object serialization. It can dump and load variables to/from files. To see more about this module, you can check it out here.

In all, this project has extensively used python’s dictionaries to store all the needed data. Even our list of available actions is stored in a dictionary. Needless to say, this project has given me greater insight into dictionaries, even more so than Homework 4 did, which dealt with maintaining an inventory of parts.

Updated Final Project

We have decided to make each room a folder. However, instead of having folders in folders for our room layout, we will have all the room folders in one subdirectory. We have also decided to use multiple files in each folder for the different actions to use. We have split the project up amongst ourselves. Two people will be coding in python and two people will write the room descriptions, action files, etc. We already have a basic implementation of the project, all we need to do is add some actions, add the room descriptions, and action files.

Final Project and Group Meetings

In the past two weeks, I have met with my final project group twice. We have decided to create a text based adventure game for The Walking Dead. The structure of the game will be based on the Linux filesystem. Each folder will be its own room, with the different directions you can move. For instance the parent folder will go back and child folders to go left/right. Items and other actions will be additional files is the folders. Instead of having the entire game text be in the main python program, we have decided to break it up. We have come up with two ways to do this.

  1. The room description and items have their own text file that the python script will read from. In this case, the program would only need to know its folder location and any items picked up. This would make it easy to create a save game addition.
  2. Every folder has its own python script. In this case, the program would only know the folder location and to call the python script of the folder and wait. The folder python script would contain the room description as well as all actions and items. This would make saving the game be more difficult and would add complexity in keeping the inventory from room to room.

Both cases have different complexities, however, I personally think that case 1 would be the more elegant way to implement the idea.

If anyone has another idea on implementation, feel free to comment.

Python Programming – reposted

I originally posted this on Sept 19th but it was on the wrong blog. I am re-posting to the correct blog.

Having programmed in C++, Java, Matlab, and some low level languages I thought programming in python would be a piece of cake. This isn’t turning out to be the case. I have about 21 more hours to complete homework 3 and I am far from having it down. Even when going through the “Learn python the hard way” exercises I am not prepared for the homework assignment. I feel like the assignments cover things that aren’t mentioned anywhere in the LPTHW book. When asking others for help they send me the link to LPTHW and tell me to google what I need because python is so well documented.

I don’t really like that kind of learning for a programming language. I know many people had to learn it this way for C++ in the intro class and they struggled with it as well. I’d rather have a separate class for python or allocate more time for python in class. When learning a language you should learn all of the ins and outs instead of a general overview. This opinion may be biased based on the fast approaching due date for HW3 so don’t judge this rant too harshly.

Start of week 7

Its hard to believe that the semester is only half over.  I spent this past weekend catching up on all of my python exercises.  I had fallen almost 12 exercises behind, but was able to catch up.  Python has been relatively simple to learn.  Its just a new syntax, but relatively similar to java and c++.  Maybe its just my experience with my other two languages that allow me to catch on to it so quickly.

I’m still not using my Debian partition enough, but that’s still mostly do to laziness.  The fact that I am able to use programs through cygwin lets me appear to be using linux for the homeworks.

I also attempted the practice midterm today.  Most of the questions weren’t too bad, but I haven’t figured out how to save the output work that I was doing, beyond a print screen.  So I will have to look into that before the midterm on Wednesday.  But in all the questions weren’t hard, and i was able to accomplish pretty much everything without too much of an issue.

Homework 4: Inventory Management

Homework 4 turned out to be a little more confusing than anticipated. It was the first time using a data structure rather than just a variable. The requirement of the assignment was to write a python script that would take in an inventory file and manipulate the data based on commands provided through standard in. In the description, the instructor provided some tips on using dictionaries. I could not comprehend how to successfully implement a dictionary for the assignment. I ended up just thinking about the assignment as if I were doing it in c++. Instead of the dictionary, I ended up using a 2D list. I am sure that if a dictionary was implemented, the assignment would have been much easier. As for the manipulation part of the assignment, everything was pretty straight forward. The main problems I had, were that “Quantity” was an int, and it would need its own if statements to account for that. Also, when writing the sort function, I had to learn about key=lambda.

Intro to Unix ECE 2524 Entry #5

So the python homework do this Wednesday has been the toughest python assignment so far. While it was the hardest, I think it was the most useful to implement, and I think learning how to write our own protocol and such was a useful exercise to do.  I found the dictReader and dictWriter functions to be very helpful when working on this assignment as they allowed me to read in data and immediately put it into a dictionary with no parsing and work needed on my part. It even took the first line as field keys for the dictionary.  Writing the dictionary back to the file was just as easy as reading from it was, and, after learning how to do this, the rest of the assignment wasn’t too bad.  I did have some trouble getting the delete command to delete multiple items in the list but with list comprehension this proved to be a fairly easy task. I wasn’t however able to get the sort by quantity to sort by integers rather than strings. I couldn’t figure out how to set types for the dictionary values by the way that I was creating the dictionary from the data read from the file. Nevertheless, I think I got all the necessary pieces of the code working as they should.

As for ECE3574, we had our easiest homework so far which required recursively moving through directories and determining the sizes of those directories. Qt has some very nice classes to help with this task such as QDir and QFileInfo. QDir allowed me to pull everything was in a current directory into a list of QFileInfo objects. QFileInfo has very helpful functions to determine whether the object is a directory or a file, and the size of whatever object it contains. After figuring these things out, it was only a matter of setting up the recursive routine properly. Parsing the arguments passed wasn’t too bad either, although this is a time where I would have liked to use the argparser in Python.  For whatever reason QtCreator did not like the -v argument passed on the command line, and would run nothing when it was passed. I’m still not sure why this is the case.  Besides that though the homework was fairly easy.

Response to “Advanced Python exercises”

Recently Matt brought up some good points in his post Advanced Python exercises.  First, the more easily addressed one:

To break up a Python program into multiple functions, just store related functions in a separate `.py` file, then in the main source use import

For example, if you have a file named `hello.py` that contains

def greeting(string):
    return "Hello, {}".format(string)

Then in your main source file (located in the same directory), you can import `hello.py` and all the functions will be available from the `hello` namespace:

import hello

print hello.greeting("world")

Easy as .py! (sorry)

Also in the post Matt talked about Python’s use of “try” and “except” as a means of flow control, as an example:

try:
    mynumber = float(line)
except ValueError as e:
    sys.stderr.write("We have a problem: {}".format(e))
else:
    print "We have the number {}".format(mynumber)

He said “if complex return types are needed such that you’re throwing exceptions to communicate logic information rather than true fatal errors, your function needs to be redesigned.” which I agree with. But I disagree that Python itself relies on this technique, or encourages it, though of course individual developers may miss-use it.

Like the programs they are a part of functions should be written to do one thing and one thing well. In the preceding example the function float converts its argument to a floating point value. The name of the function makes it very clear what it does, and it does its job well. If it can’t do it’s job, then it raises a ValueError exception.  All other built in and library functions I’ve seen work the same way.  Think about the alternative without exceptions, for example, C:

double n = atof(line);
printf ( "We have the number %f\n" , n);
//Except if n == 0 it could be because there was no valid numeric expression in line

According to the documentation for atof:

On success, the function returns the converted floating point number as a double value.
If no valid conversion could be performed, the function returns zero (0.0).
There is no standard specification on what happens when the
converted value would be out of the range of representable values by a double. 
See strtod for a more robust cross-platform alternative when this is a possibility.

This is less than ideal. If we wanted to check if an input even contained a valid numeric string (which we usually would) we’d have to work harder. The strtod alternative provides a means to do that, but we’d still have to do an explicit check after calling the function.  Other C-style functions use a return code to indicate success or failure.  It is also extremely easy to forget to check return codes, in which case the problem may only manifest itself in a crash later on, or worse, not at all, but instead just produce bad output.  These types of problems are very hard to track down and debug.  Using exceptions the program crashes precisely where the problem occurred unless the programmer handles that particular exception.

So to summarize: Each of your functions should have a well-defined job.  They should do only one job and do it well.  If they can’t do their job because of improper input, then they should raise an appropriate exception.  I think following that idiom results in cleaner, easier to debug code.  You could certainly still return complex data types where appropriate, but trying to incorporate success/failure information in a return type will often lead to difficult to debug errors when the programmer forgets to check the return status!