Python
A Python
No, actually...
Why Python?
(Other options: PHP, Perl, Ruby, Java, Lisp, Haskell, Erlang...)
- Succinct (~1/10 LOC compared to Java)
- But not too succinct (no !@#^%!@#^!@#); clean, readable syntax
- "Batteries included" - "there's a library for that"
- Flexible (powerful introspection; has features to allow for various programming paradigms: OO, functional, simple scripting, etc)
- Large and friendly community; lots of sources of help. Also jobs; used by many major companies (e.g. Google)
- Monty Python references!
Diving in: the shell
Start up an interactive Python shell by typing python
at your Linux/OSX command-line shell:
carljm@kale:~$ python Python 2.5.2 (r252:60911, Jul 22 2009, 15:35:03) [GCC 4.2.4 (Ubuntu 4.2.4-1ubuntu3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>
Just as you'd expect...
>>> width = 20 >>> height = 5*9 >>> width * height 900 >>> 3.3 / 1.12 2.9464285714285712 >>> first_name = "Carl" >>> last_name = "Meyer" >>> full_name = first_name + " " + last_name >>> full_name 'Carl Meyer' >>> ^D
Note that there is no need to declare variables or specify a type. Just assign a value to the variable and it pops into existence.
"Hello World"
Playing around in the interactive interpreter is a useful way to quickly
try out an idea, but at some point we want to write actual programs. First,
use cd to change to whatever directory you want to save your
Python work in (probably "/Volumes/HOMES/My Documents" or
/Volumes/HOMES/Classes/COMM385/yourname). Then fire up Emacs
to edit your first Python program:
carljm@kale:~$ emacs hello.py
Doesn't take much:
print "Hello, World."
C-x C-s to save the file,
C-z to temporarily put Emacs in the background and get
back to your shell. Then run your program:
carljm@kale:~$ python hello.py Hello, World.(When you run Python with a file as the first argument, it runs the code in that file instead of giving you an interactive shell prompt.)
Now type fg at the shell prompt to bring Emacs back to
the foreground, then C-x C-f to open up a new
file named util.py.
Functions
Write a simple function to return the maximum of two numbers:
def maximum(x, y):
"""
Return the larger of its two arguments.
"""
if x > y:
return x
else:
return y
Functions are defined with the def keyword. Then comes
the name of the function, followed by the list of parameters (in
parentheses).
Docstrings
Under the function declaration is a docstring which documents the purpose of the function. This is not strictly required, but it's a good practice.
Triple-quoted strings in Python can span multiple lines, which lets you write more readable docstrings.
Indentation
Python uses indentation to define nested blocks of code. In many
languages (Java, C/C++, Javascript, PHP) you use
curly-braces {} for this purpose, and indent properly to
make it readable. In Python, just indent it the way you would anyway,
and that determines the structure. (Bonus: no pointless arguments
about how to arrange the curly-braces.)
Also, notice that any line which begins an indented block
(def ... :, if ... :,
and else:) ends with a colon. Indented blocks in Python
are always set off by a colon.
Imports
Save the util.py file. Now we can import
it and use it from the interactive shell:
>>> import util >>> util.maximum(3, 7) 7
If we'll be using the maximum function often, we can
also pull it out of the util namespace into our global
namespace:
>>> from util import maximum >>> maximum(5, 4) 5
You can use import the same way from a program in
another file.
Lists
So far, we've seen numbers (both integers and floating point) and strings. Python also has several compound datatypes. The simplest is the list:
names = ["Rolando", "Kate", "Pat"]
for name in names:
print name
ages = [33, 27, 19]
print ages[0], ages[1], ages[2]
Save that code in a file and run it. What does it print?
Note that you can access items in a list by their (0-based) index, but you don't need an index variable to loop through the items in a list.
Dictionaries
What if we want to associate these people's names with their ages? Use a dictionary:
people = {"Rolando": 33, "Kate": 27, "Pat": 19}
for name in people:
age = people[name]
print name, age
Save and run this.
Dictionaries have keys associated with values. When we loop through
a dictionary using for, we get the keys. When we index
into a dictionary, instead of using a numeric index, we use the key to
get the value.
Reading
For next week: read chapters 2 & 3 in Dive Into Python.
Some exercise for your Python
- Write a function that can take a list of numbers as its sole argument, and return the largest number in the list.
- Write a function that takes as its argument a dictionary mapping people's names to their ages, and returns the name of the oldest person.
- Write a function that takes as its argument a list of numbers, and returns a list of each number squared (so [1,2,3,4] passed in would result in [1,4,9,16] being returned). Bonus points if you use a "list comprehension."
Where to get help
- Questions? Drop me a line on email (carljm@goshen.edu) or Google Chat (carl.j.meyer) or AIM (cjm46543)
- interactive documentation:
>>> help - online documentation: docs.python.org
- Dive Into Python book: diveintopython.org
- Stack Overflow (programmer Q&A site): stackoverflow.com
- #python IRC channel at irc.freenode.net