Sample Programs

Introduction to Programming and Algorithm Design (COP 1000)

This is an index to sample Python programs, roughly organized by chapter in our text. The best way to learn a programming language is to study, modify, and execute existing programs.

Note: if you are looking for an example of how to use a particular technique in Python (like "sentinel loop" or "slicing"), you can use the your browser's "Find in this Page" feature to locate it in the list below.


Variables, expressions, and statements (Chapter 2)

f2c.py
This IPO program converts temperatures from the Fahrenheit to Celsius scale. Demonstrates the use of the built-in round() function. Also shows how to use the built-in raw_input() function to hold open the command window in which the program is running if you are executing it outside the IDLE (as when you double-click on the program icon).

Functions (Chapter 3)

gpa1.py
This program shows the use of the built-in conversion function float() to coerce a value to force floating-point division. Use of the str() function to build an output string is also demonstrated.
sqrt1.py
Demonstrates the import of a module and the use of math.sqrt()
newline.py
Demonstrates how to define and call functions
splash.py
Uses a void function to draw a simple program splash screen (what the user sees when the program is started).
fnln.py
Displays a name first name first and last name first using functions. Also demonstrates use of raw_input to input string data.
gpa2.py
Uses a fruitful function and composition to compute grade point average
triArea.py
Calculates the area of a triangle using a fruitful function. It also shows how to prevent a newline after a print statement by using a trailing comma.
triArea2.py
Similar to the program above, but allows the user to input values for the base and height of the triangle.

Case study: Interface design (Chapter 4)

polygon.py
Introduces TurtleWorld and draws a simple half-square
polygon4.py
Draws polygons with multiple Turtle instances
polygon5.py
Demonstrates how to encapsulate functionality by writing a function to draw a square
polygon6.py
Shows how to generalize a function by parameterizing factors to control how the function works
polygon7.py
More generalization of a function
circle.py
Demonstrates interface design by constructing a function that allows a client to call a function in a "natural way"
circle2.py
Illustrates the concept of refactoring, by taking a working function and breaking it down into more elemental functions
circle3.py
Shows how to use "docstrings" to document function interfaces.

Conditionals and recursion (Chapter 5)

getA.py
Demonstrates conditional execution (single selection) and use of the round() function.
passfail.py
Alternative execution (dual selection) is used in this program to determine if a passing grade was obtained.
calcHonors.py
A chained conditional (multi selection) structure is used in this program to determine the type of honors received based on GPA
calcHonors2.py
Another chained conditional structure, but done in the reverse order from the above program
evenodd.py
A nested conditional structure is demonstrated in this program that determines if a number is odd or even.
printlog.py
The return statement is used here to exit a function
countdown.py
This program demonstrates recursion, using recursive function calls to display a countdown from a user entered value; it also demonstrates use of the sleep() function from the time module to slow down the program
gcd.py
Euclid's algorithm for finding the greatest common divisor (GCD) of two integers is implemented in this program, which uses a recursive function to calculate the GCD.
tomato.py
Use of raw_input to input a string is shown in the program. A chained conditional structure is used in the fruitful function calcPrice to obtain the correct price per pound for the type of tomato purchased.

Fruitful functions (Chapter 6)

circum.py
Calculates the circumference of a circle using a fruitful function
absolute.py
Uses a function to calculate the absolute value of a number; it demonstrates use of multiple return statements
intercept.py
This program computes the y-intercept of a line, given the coordinates of two points on the line. The design of the program includes composition one function (intercept) calling another (slope) to simplify development
islower.py
An example of a boolean function that checks a character for lowercase.
factorial.py
Uses recursion to calculate n!
fibonacci.py
Another recursion program, this time to calcualte fibonacci(n). It also introduces the for loop and built-in range() function.
factorial2.py
A revision of the previous factorial program to add type checking and range checking for input.

Iteration (Chapter 7)

log2.py
Displays a table of log base 2, produced with the while statement; also demonstrates use of the tab character '\t'
power2.py
Displays the first 16 powers of 2 with a loop
printTable.py
Produces a multiplication table of user-defined size, using iteration
factorial_nr.py
Calculates the factorial of a number using iteration rather than recursion.
factorial_nr2.py
Calculates the factorials of 1-10 using iteration and displays the results in a table
lh.py
Demonstrates how to code a loop-and-a half with the break statement
sentinel.py
Uses a sentinel-controlled loop to convert square feet to acres.
sqroot.py
Calculates a square root using Newton's method; demonstrates iteration with a loop-and-a half, and using a desired precision (result) to terminate the loop

Strings (Chapter 8)

twhile.py
Displays the ASCII codes of the characters in a string. The string is traversed as an array, using a while loop. The use of the built-in function ord() is also demonstrated
tfor.py
Produces the same output as the program above, but the string is traversed using a for loop.
findch.py
Demonstrates a function that searches a string for a specified character and returns its index if found, or -1 otherwise
findch2.py
Modifies the above program so that the functions takes a third parameter, the index in the string where is should start looking; this program also demonstrates use of a Boolean "flag" variable to indicate a condition in the program (whether any occurrences of the character were found in the string)
countch.py
Shows how to use a counter to count the number of times a specified character occurs in a string
in_both.py
Uses the in operator and a string traversal to identify the characters common to two strings.

Case study: Word play (Chapter 9)

Note: all the programs in this chapter require this file: words.txt; see the Lecture Notes for this chapter for source

longWords.py
Finds words in the English language with at least 20 letters; demonstrates string traversal and accessing files
hasNoE.py
Finds words that do not contain the letter 'e'; demonstrates Boolean search functions
avoids.py
Finds words that do not contain any of the letters specified
uses_only.py
Finds words that consist only of the letters specified
is_abecedarian.py
Finds words whose letters are in ascending alphabetical order

Lists (Chapter 10)

caps.py
Demonstrates mapping by creating a list of capitalized names from another list; uses the string method capitalize
mult7.py
Demonstrates filtering by creating a new list from a list of integers, including only those that are multiples of 7
popall.py
Shows how to use the list pop method to remove elements from a list, in effect printing it backwards
squareList.py
Squares the elements of a list of numeric values with a non-fruitful function. Demonstrates how modifying a list parameter modifies the list in the calling function
countWords.py
Demonstrates use of the split method in the string module to separate an input string into a list of words.

Dictionaries (Chapter 11)

countch.py
Uses a dictionary to count the occurrences of a character in a string
countch2.py
Counts characters in a string using a dictionary and the get method
countch3.py
Shows how to use a dictionary traversal to display the count of characters in a string
counch4.py
Counts characters in a string, using the keys method to sort the ouput
revlookup.py
Demonstrates how to perform a dictionary "reverse lookup" from value to key
invert.py
Inverts a dictionary, mapping the values to keys, and the keys to lists of values.
fibonacci2.py
Generates the Fibonacci series up to a user-specified limit, using recursion
fibonacci3.py
Generates the Fibonacci series up to a user-specified limit using a dictionary to hold values of already-calculated Fibonacci numbers
fibonacci4.py
Same as above, but also display the type of the Fibonacci number generated, to demonstrate automatic conversion from int to long

Tuples (Chapter 12)

cylData.py
Determines the surface area and volume of a cylinder, using a function that returns a tuple. Also demonstrates tuple assignment with input(), and using a tuple with print
avg_all.py
Shows how to use variable-length argument lists.
zip_list.py
This program combines two sequences into a list of two-element tuples using the built-in zip function.
zip_list2.py
This program shows how to traverse a list of tuples created with the zip function, using two variables, one for each element of each tuple.
create_dict.py
This program creates a dictionary by combining two sequences with zip into a list of tuples that are used as key-value pairs
directory.py
Shows how to create a simple telephone directory with a dictionary, the keys of which are a tuple of (last_name, first_name) form.

Case study: Data structure selection (Chapter 13)

randomInt.py
Demonstrates how to generate a list of pseudorandom numbers
countRandom.py
Shows how to count the number of occurrences of a particular random number in a list to generate a histogram

Files (Chapter 14)

createfile.py
Creates a text file from keyboard input using the write() method.
createfile2.py
Same as the above program, but asks the user where to save the file.
readfile.py
Reads a the text file written above, inputting the entire file into a string with the read() method, then displays the string.
readfile2.py
Reads the text file one line at a time with the readline() method, displaying each line as it is input.
readfile3.py
Reads the text file, inputting each line into a list of strings, then displays each line by iterating through the list.
readfile4.py
Reads the text file by iterating through file, one line at a time.
cremail.py
Creates a text file. Shows how to interactively obtain the name of the file to create.
ioexception.py
Demonstrates IOError exception handling.
ioexception2.py
Shows how to use exception handling to open a file for input, or create an empty file if it does not exist.
email.py
Program to maintain an email address list. Illustrates techniques for adding, updating, and deleting records in a file.

Classes and objects (Chapter 15)

point1.py
Shows how to declare a simple class and use instances of that class as arguments to functions
rectangle1.py
Demonstrates a class that contains an instance of another class as an attribute.

Classes and functions (Chapter 16)

time1.py
Introduces a user-defined class Time that represents a 24-hour clock, and includes two functions for working with Time objects
time2.py
Demonstrates a pure function that will add two Time objects (but which is a little buggy)
time3.py
Corrects the addTime() function in the program above.
time4.py
Demonstrates a modifier function that increments a Time object
time5.py
Rewrites the increment() function above as a pure function
time6.py
Shows how Time functions can be simplified by providing a facility to convert base-60 Time objects to equivalent base-10 integer seconds, and back.

Classes and methods (Chapter 17)

time14_1.py
Demonstrates implementing a simple method for the Time class
time14_2.py
Shows how to write a method that uses a parameter
time14_3.py
Updates the Time class to include a method that compares to Time objects
time14_4.py
Demonstrates how to write a method that takes an optional argument, assigning a default value to a parameter if the argument is omitted
time14_5.py
Shows how to write an __init__ method to initialize and validate instance variables
time14_6.py
Demonstrates the use of a __str__ method to construct a string version of an object
point14_1.py
Another demonstration of the __str__ method, this time for the Point class
point14_2.py
Demonstrates how to implement operator overloading; in this case, by overloading the addition operator for the Point class
time14_7.py
Another demonstration of operator overloading; here, two Time objects are added

Inheritance (Chapter 18)

cards1.py
Develops a Card class simulating playing cards; shows how to use class attributes to decode card values into strings
cards2.py
Shows how to add a __cmp__ method to override the relational and equality comparison operators to compare two Card objects
deck1.py
Demonstrates composition by creating a Deck class made up of Card objects
deck2.py
Adds a shuffle method to the Deck class
deck3.py
Adds various other methods to the Deck class to make it easy for a client card-playing program to use
hand1.py
Shows how to create a new class by inheriting from an existing class
hand2.py
Demonstrates how to override a method from the parent class when creating a new child class with inheritance
cardGame.py
This code is meant to be imported as a module for programs dealing with card-playing simulations; it includes the classes Hand, Deck, Card and CardGame
oldMaidHand.py
Shows how to import the cardGame module and, with inheritance, create a new class OldMaidHand
oldMaidGame.py
The complete simulation of Old Maid

Graphics with Python

  • Note: All these programs require you to download the graphics.py module, and save it in your Python folder, in the subfolder Lib\site-packages
grades.py
Uses graphics to enhance a programs output; in this case, displaying bar graphs of three grades and their mean
throwRock.py
Uses graphics to demonstrate the flight of a rock thrown off a building at different velocities
triangle.pyw
Shows how to use the mouse for input to draw a triangle
button2.py
Shows how to assemble an interactive Button class from simpler widgets
convert_gui.pyw
Uses a "dialog box" to obtain text input to convert temperatures with a GUI
throwRock2.pyw
Updates the above program to allow a user to input an initial velocity for the rock
 Updated 12.13.2010