Installing/Using/Running Python on a Mac, for Beginners

I just had to do a Python assignment for my Computer Science class. The Internet instructions were extremely unhelpful so here goes. A good site to learn about Python is DiveIntoPython.

There isn’t an API for Python like there is for Java but this is the official reference. Every method is in here somewhere but you have to dig for it, there’s no search function which is annoying.

If you need to write whole classes in Python:
Download TextWrangler, open it, and adjust the bars at the bottom to say Python, Unicode (UTF-8) and Unix (LF). When you are done, save the file as (filename).py. TextWrangler is my favorite app to write code in because you can pick the Monaco font (my favorite) and it colors the code based on what you wrote.

To test the file click on the #! in the menu bar at the top and either click “Run” or “Run in Terminal.” This will run through your code and catch errors. If you have defs (functions, methods, whatever you call them) in a class, they are hard to run. Test the defs by running your class and calling the defs you want to test at the zero-indent level. If the defs still don’t run, set them equal to a value. So say you want to test the function

def kevin (b):
print b

right below it, with no indent, write

a = kevin(“jeff”)

and then see if it prints “jeff” when you run the code. I couldn’t figure out how to run the defs straight from a command line.

The other way to test your code is by interactions. To test interactions (one line of code at a time, with a prompt line) open Terminal (in Finder open Applications, then open Utilities) and type python, then hit “Return.” Some dialog should come up and then there should be three arrows like this

>>>

This means that you can now type Python code and test it. Running code and testing it in interactions are the two main ways to write and test your code.

If you have to test Regular Expressions (if you don’t know what they are, don’t ask), follow the instructions here to download MacPython. Once you’ve done that, find the file redemo.py and run it. It lets you edit a regular expression and a string to match it against in real time.

Advertisements

Leave a Reply

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