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.
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 Fib.py:
#calculate the nth digit of the Fibonacci sequence
a,b = 1,0
for j in range(n):
a,b = a+b,a
for j in range(10):
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 Fib.py. Mine was in “colcarroll/mystuff/blog”. Once there, just type “
python Fib.py“, 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.