Getting started with Python, on a mac

I think the default Mac terminal colors are different from this, but you can change them in "preferences"

This is intended as a quick guide, since one of the things that got me into programming was realizing how quickly I could start on my Apple laptop without installing anything.  As a practice first project, we’ll first compute the first 10 Fibonacci numbers, then write a function that will do this.
1. Finding Python.  The easiest way to get started is to just hit “cmd+space” (this opens spotlight: my favorite Mac feature), then type “terminal”, and open the terminal.  After that, it is as easy as typing python, and you have either a powerful calculator, or a way to start writing scripts.
2. Fibonacci. As a nice first calculation, we’ll save two variables to initialize the Fibonacci sequence, then run a loop 99 times (I had to play around a bit to see how the loop count corresponded to where in the Fibonacci sequence I was). See the image for this section.  Note that the spaces are very important.  You need to end lines with a colon, and start lines after the colon by indenting.  See below for more proper indenting.

Wikipedia claims the first Fibonacci number is 0, which I am ignoring for this post.

3. Function. Now to write a helper function that I can use to calculate many such numbers, I will open a text file (just in TextEdit), type in the code below, and save it as

def Fib(n):
#calculate the nth digit of the Fibonacci sequence
a,b = 1,0
for j in range(n):
a,b = a+b,a
return a

for j in range(10):
print Fib(j)

You can also see this post in progress behind the semi-opaque terminal!

4. Running a script. Now go back to the terminal window, hit “ctrl+d” to get out of Python, and navigate to the folder where you saved Mine was in “colcarroll/mystuff/blog”. Once there, just type “python“, and the terminal will print out anything you asked to be printed out. Above, I print out the first 10 Fibonacci numbers.

Cheers! Now go find a proper introduction. Or use Project Euler.


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s