Tufts OpenCourseware
Search
Author: Ming Y Chow

Python Programming

Python Overview

  • And now for something completely different
  • General purpose, high-level, open source programming language
  • Commonly dubbed as a scripting language
  • Very flexible and agile
  • Invented by Guido van Rossum, Python's Benevolent Dictator for Life (BDFL), now at Google
  • Name is based off of Monty Python
  • Usage
    • Google App Engine
    • BitTorrent
    • Software for One Laptop Per Child XO
    • Google
    • YouTube
    • Web applications and web servers
    • System administration
    • Scripting language for many software packages including Blender and Maya
    • Reddit

From a Programming Language Standpoint

  • Interpreted
  • Supports object-oriented programming (OOP)
  • Dynamically typed (i.e., variable can refer to a value of any type)
  • Automatic memory management
  • Supports functional programming
  • Embedding and extending in C

Why Python?

  • Platform-independent and portable
  • Versatility; what you can do: system utilities, games, Internet scripts, rapid prototypes, database access, image processing, web applications
  • Generally very fast (near the speed of C)
  • Excellent community support
  • Truly open source
  • >>> import this
    The Zen of Python (by Tim Peters)
    
    Beautiful is better than ugly.
    Explicit is better than implicit.
    Simple is better than complex.
    Complex is better than complicated. 
    Flat is better than nested.
    Sparse is better than dense.
    Readability counts.
    Special cases aren't special enough to break the rules.
    Although practicality beats purity.
    Errors should never pass silently.
    Unless explicitly silenced.
    In the face of ambiguity, refuse the temptation to guess.
    There should be one-- and preferably only one --obvious way to do it.
    Although that way may not be obvious at first unless you're Dutch.
    Now is better than never.
    Although never is often better than *right* now.
    If the implementation is hard to explain, it's a bad idea.
    If the implementation is easy to explain, it may be a good idea.
    Namespaces are one honking great idea -- let's do more of those!

Python in Games

  • Civilization IV
  • Battlefield 2
  • EVE Online
  • Disney's Pirates of the Caribbean Online (MMORPG)
  • Pygame
  • More...

Environment

Why Did I Switch the Course From Java to Python?

  • More non-Computer Science students than Computer Science majors
  • Need to teach Object-Oriented Programming, classes, and objects first! WTF?!?!?
  • Java is very heavy in terms of the number of packages available in the JDK and in terms of code writing
  • Okay I admit it, Java's reputation in game development is not very strong
  • At times, non-CS students could not understand the programs they were coding (or using for that matter)
  • Style is important. In Python, you are forced to use indentation / code blocks
  • I am a firm believer that one should read code like it is an English paper. Recall The Zen of Python

The Structure of a Python Program

# Last updated on July 18, 2010
from random import randint

min = 1
max = 100
secret = randint(min, max)
print("Welcome!")
guess = 0
numGuesses = 0
while guess != secret:
	guess = 0
	while guess < min or guess > max:
		g = input("Guess the number between " + str(min) + " and " + str(max) + " (inclusive): ")
		guess = int(g)
		if guess < min or guess > max:
			print "You bozo, your guess does not count.  Try again."
	numGuesses = numGuesses + 1 # Anything interesting?
	if guess == secret:
		print("You win!  It took you " + str(numGuesses) + " guesses.")
	else:
		if guess > secret:
			print("Too high")
		else:
			print("Too low")
print("Game over!")

Preliminaries

  • File extension: .py
  • For experienced programmers, some of the "usual gang" of stuff will look a bit different
  • Conformity is important in Python
  • Code blocks - code is structured by whitespaces or tabs (so no more flame wars on style). No more curly braces ({})
  • Any line that ends with a colon (:) will tell the Python compiler that the next line should be a sub-code block
  • Use # for a comment, not // or /* */
  • No semicolon (;) at the end of statements

Interpreter

  • Very much like the Unix / Linux shell, Command Prompt
  • On executing the interpreter by itself (i.e., python), it reads and executes commands interactively. The prompt: >>>
  • On executing the interpreter with a file as standard input, it reads and executes a script from that file. We will primarily use this option.
  • List of built-in functions (python.org)
  • Example: len("hownowbrowncow") returns the length of the string "hownowbrowncow" (14)
  • To make your Python script an executable (e.g., shell script) on a Unix / Linux system, add the line #! /usr/bin/env python to the top of your script and change the file's permission to 755 or chmod 755 YOUR_SCRIPT

Arithmetic Operators

  • The usual gang: +, -, *, /, %
  • ** - exponent
  • // - floor division

Truth and Booleans

  • True
  • False

Comparison Operators

  • The usual gang: <, >, >=, <=, ==, != (or <>)

Assignment Operators

  • The usual gang: =, += (e.g., c+=a is equivalent to c = c + a), -=, *=, /=, %=
  • **= - c**a is equivalent to c = c ** a
  • //=
  • No increment or decrement operators (++ or --)

Logical Operators

  • not
  • and
  • or

Operator Precedence

Variables

  • These are all legal:
    • foo = 1
    • foo = "1"
    • foo = '1'
    • foo = 1.1
  • Variables can be re-assigned at any time to different types of data; very flexible

Control Flow (if-then)

  • 	if STATEMENT:
    		...
    		...
    	else:
    		...
    		...
    
  • 	if STATEMENT:
    		...
    		...
    	elif STATEMENT:
    		...
    		...
    	elif STATEMENT:
    		...
    		...
    	else:
    		...
    		...
    
  • No parentheses around conditional statement
  • Example: see guessing game above
  • Sorry folks, Python does not have a switch statement (which could have come in handy)

Strings

  • Can be enclosed in single quotes or double quotes. The difference?
  • >>> 'spam eggs'
    'spam eggs'
    >>> 'doesn't'
    "doesn't"
    >>> "doesn't"
    "doesn't"
    >>> '"Yes," he said.'
    '"Yes," he said.'
    >>> ""Yes," he said."
    '"Yes," he said.'
    >>> '"Isn't," she said.'
    '"Isn't," she said.'
    
  • Can span multiple lines via newline character in double-quoted string
  • String concatenation: by + or * (repeat). Examples:
    • str = 'The' + 'Fonz' # str will become 'TheFonz'
    • str = 'TheFonz' * 5 # str will become 'TheFonzTheFonzTheFonzTheFonz'
  • Can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0
  • "Slicing" examples (for s = "Hello"):
    • s[4] is 'o'
    • s[1:] is 'llo'
    • s[-4] is 'e' # 4th character from the end
    • s[:-3] is 'He' # going up to but not including the last 3 chars
  • List of string methods: http://docs.python.org/library/stdtypes.html#string-methods

pass Statement

  • Does nothing
  • Commonly used as a placeholder

Functions

  • Starts with keyword def
  • Parenthesized list of formal parameters; arguments are passed using call-by-value
  • Documentation string (or docstring) - the first statement of function body that describes the purpose of the function. This is optional but is excellent practice. Enclosed with three quotes """
  • The return statement returns with a value from a function
  • Example: fibonacci.py

Data Structures

  • List - written within square brackets [] (a.k.a., array)
  • Example 1: jacksons = ['Michael', 'Janet', 'Jermaine', 'LaToya']
  • The usual gang: indexing starts at 0
  • Example 2: jacksons[2] returns the third element in the list (Jermaine)
  • Watch out! The assignment operator = does not make a copy of a list but just a pointer in memory to it
  • Like slicing a string, you can also slice a list
  • List methods: http://docs.python.org/tutorial/datastructures.html
  • Tuple (or sequence) - written within parentheses (). However, is immutable. That is, you cannot add, remove, or change items once the sequence is created.
  • Dictionary - written within curly braces {}. Also known as a hash or an associative array. Assign a value to a key which can be a string or an integer index
  • Example 3: emails = {'TheRock':'therock@knowyourrole.com', 'William Bonney':'billythekid@yahoo.com', 'Homer Simpson':'hoj@fox.com'}
  • Example 4: dict.py
  • Example 5:
    cats = {}
    cats['fat'] = 'Garfield'
    
  • Dictionary methods: http://docs.python.org/library/stdtypes.html#typesmapping

Loops

  • while - usual gang; see guessing game example above
  • for - does not iterate over an arithmetic progression of numbers but instead iterates over the items of any sequence (e.g., list). Use the in keyword to test if an element is in a set / list. Two ways:
    • for i in range(10): # go through numbers from 0 through 9
    • list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
      for i in list:
      
  • Example:
    for key in emails:
    	print k + " => " + emails[k]
    
  • No do-while

Input / Output

  • print (duh!)
  • For C buffs, format string lives! Use %. Example:
    import math
    print 'The value of PI is approximately %5.3f.' % math.pi
    
  • input()
  • raw_input()

File Input / Output

  • open() function - Opens a file for reading, returns a file handle (pointer to the first line of the file)
  • Call the close() method on the file handle to close reading of the file at the end
  • Example 1 (reading):
    f = open('foo.txt', 'r')
    for line in f:
    	print line
    f.close()
    
  • File permissions: 'r' = read, 'w' = write, 'a' = append, 'r+' = read-write
  • On Windows, 'b' appended to the mode opens the file in binary mode
  • f.readline() - Reads a single line from file
  • f.write() - Write to file
  • Example 2 (writing; what is the output?)
    # What is the output?
    
    f = open('test.txt', 'w')
    f.write("Hi!")
    f.write("Ho!")
    f.close()
    

Modules

  • The purpose of a module: a way to put Python definitions and statements in a file and use them in a script or in an interactive instance of the interpreter
  • Allows for code reusability
  • Import a module in a script or the interpreter via import
  • Use the module's name followed by a dot (.) to access module's functions
  • from keyword - loads a Python module into the current namespace, so that you can refer to it without the need to mention the module name again (i.e., no "dot" notation)
  • Example 1: urltest.py
  • Example 2: urllib and urllib2
  • Example 3: os
  • Example 4: math
  • Example 5: pickle (very powerful)
  • Example 6: random
  • Example 6A:
    	import random
    
    	randnum = random.randint(1, 100)
    	print randnum
    
  • The dir() function - lists the names a module defines

Testing Module

  • if __name__ == "__main__":
  • Modules are objects, and all modules have a built-in attribute __name__
  • If you import the module, then __name__ is the module's filename, without a directory path or file extension
  • If you run the module directly as a standalone program, then __name__ will be a special default value __main__
  • Example: maintest.py

Objects

  • An object is a thing obeying a set of conditions
  • A condition can assert the existence of a piece of data or a function inside the object. Data and functions that must be present are called members
  • An instance of an object is one of the things obeying the conditions
  • A description of an object (with all conditions specified) is called a class. This is nothing more than a list of things that must be defined before you have an object.
  • The superclass (or base class) - Defines "generic" instance variables and methods that apply in many situations
  • The subclass (or derived class) - Specializes, extends, or inherits from a superclass need not give new implementations for the general methods, for it inherits them by adding conditions (functions and data). Should only define those specialized methods for this particular subclass.
  • We list an object hierarchy with the most general (most super) classes at the top, and the most specific (most subordinate) class at the bottom ("is a" relationship)
  • Polymorphism is the ability of an object variable to take different forms. Overloading is a type of polymorphism. Example: + operator.
  • Everything in Python is an object

Classes

  • class ClassName:
  • Class instantiation uses function notatation. Example: x = MyClass()
  • def __init__(self): - the constructor, run when the class is instantiated. You can have multiple parameters for the __init__ method
  • def __del__(self) - the destructor (hardly needed)
  • All class methods shall have self as first parameter
  • When you call a method of an ancestor class from within your class, you must include the self argument
  • When you call your class method from outside, you do not specify anything for the self argument; you skip it entirely, and Python automatically adds the instance reference for you
  • No new
  • Classes can (and should) have doc strings too!
  • To access a member of the class (method or data attribute), use "dot notation" (.)
  • Inheritance is easy: class DerivedClassName(BaseClassName):
  • Example: class Square(Shape):
  • Unlike many other languages, multiple inheritance is supported. In layman term, a child or subclass can have more than one parent.
  • What about traditional "private" variables in a class for information hiding? They do not exist in Python! Instead, use the Python convention to put an underscore (_) prefix to an object variable name to denote it as "private"
  • Example 1:
    class Foo:
    	""" My first class """
    	def __init__(self):
    		print "Hi!"
    
    	def setx (self, x):
    		self.x = x
    		
    	def bar (self):
    		print self.x
    
    if __name__ == "__main__":
    	f = Foo()
    	f.setx(20)
    	f.bar
    
    # What is the output (and why)?
    
  • Example 2:
    class Dog:
    	""" Dog dog dog! """
    	def __init__(self):
    		""" Initializer """
    		print "A dog is born..."
    		self.name = "Fido"
    
    	def setName (self, n):
    		self.name = n
                
    	def bark(self):
    		print self.name + " says Arf!"
    
    if __name__ == "__main__":
    	brian = Dog()
    	brian.setName("Brian")
    	for i in range(5):
    		brian.bark()
    
    	lily = Dog()
    	lily.setName("Lily")
    	lily.bark()
    
    	stu = Dog()
    	stu.bark()