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)
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)
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.
Demonstrates the import of a module and the use of math.sqrt()
Demonstrates how to define and call functions
Uses a void function to draw a simple program splash screen (what the user sees when the program is started).
Displays a name first name first and last name first using functions. Also demonstrates use of raw_input to input string data.
Uses a fruitful function and composition to compute grade point average
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.
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)
Introduces TurtleWorld and draws a simple half-square
Draws polygons with multiple Turtle instances
Demonstrates how to encapsulate functionality by writing a function to draw a square
Shows how to generalize a function by parameterizing factors to control how the function works
More generalization of a function
Demonstrates interface design by constructing a function that allows a client to call a function in a "natural way"
Illustrates the concept of refactoring, by taking a working function and breaking it down into more elemental functions
Shows how to use "docstrings" to document function interfaces.

Conditionals and recursion (Chapter 5)
Demonstrates conditional execution (single selection) and use of the round() function.
Alternative execution (dual selection) is used in this program to determine if a passing grade was obtained.
A chained conditional (multi selection) structure is used in this program to determine the type of honors received based on GPA
Another chained conditional structure, but done in the reverse order from the above program
A nested conditional structure is demonstrated in this program that determines if a number is odd or even.
The return statement is used here to exit a function
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
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.
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)
Calculates the circumference of a circle using a fruitful function
Uses a function to calculate the absolute value of a number; it demonstrates use of multiple return statements
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
An example of a boolean function that checks a character for lowercase.
Uses recursion to calculate n!
Another recursion program, this time to calcualte fibonacci(n). It also introduces the for loop and built-in range() function.
A revision of the previous factorial program to add type checking and range checking for input.

Iteration (Chapter 7)
Displays a table of log base 2, produced with the while statement; also demonstrates use of the tab character '\t'
Displays the first 16 powers of 2 with a loop
Produces a multiplication table of user-defined size, using iteration
Calculates the factorial of a number using iteration rather than recursion.
Calculates the factorials of 1-10 using iteration and displays the results in a table
Demonstrates how to code a loop-and-a half with the break statement
Uses a sentinel-controlled loop to convert square feet to acres.
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)
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
Produces the same output as the program above, but the string is traversed using a for loop.
Demonstrates a function that searches a string for a specified character and returns its index if found, or -1 otherwise
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)
Shows how to use a counter to count the number of times a specified character occurs in a string
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
Finds words in the English language with at least 20 letters; demonstrates string traversal and accessing files
Finds words that do not contain the letter 'e'; demonstrates Boolean search functions
Finds words that do not contain any of the letters specified
Finds words that consist only of the letters specified
Finds words whose letters are in ascending alphabetical order

Lists (Chapter 10)
Demonstrates mapping by creating a list of capitalized names from another list; uses the string method capitalize
Demonstrates filtering by creating a new list from a list of integers, including only those that are multiples of 7
Shows how to use the list pop method to remove elements from a list, in effect printing it backwards
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
Demonstrates use of the split method in the string module to separate an input string into a list of words.

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

Tuples (Chapter 12)
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
Shows how to use variable-length argument lists.
This program combines two sequences into a list of two-element tuples using the built-in zip function.
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.
This program creates a dictionary by combining two sequences with zip into a list of tuples that are used as key-value pairs
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)
Demonstrates how to generate a list of pseudorandom numbers
Shows how to count the number of occurrences of a particular random number in a list to generate a histogram

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

Classes and objects (Chapter 15)
Shows how to declare a simple class and use instances of that class as arguments to functions
Demonstrates a class that contains an instance of another class as an attribute.

Classes and functions (Chapter 16)
Introduces a user-defined class Time that represents a 24-hour clock, and includes two functions for working with Time objects
Demonstrates a pure function that will add two Time objects (but which is a little buggy)
Corrects the addTime() function in the program above.
Demonstrates a modifier function that increments a Time object
Rewrites the increment() function above as a pure function
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)
Demonstrates implementing a simple method for the Time class
Shows how to write a method that uses a parameter
Updates the Time class to include a method that compares to Time objects
Demonstrates how to write a method that takes an optional argument, assigning a default value to a parameter if the argument is omitted
Shows how to write an __init__ method to initialize and validate instance variables
Demonstrates the use of a __str__ method to construct a string version of an object
Another demonstration of the __str__ method, this time for the Point class
Demonstrates how to implement operator overloading; in this case, by overloading the addition operator for the Point class
Another demonstration of operator overloading; here, two Time objects are added

Inheritance (Chapter 18)
Develops a Card class simulating playing cards; shows how to use class attributes to decode card values into strings
Shows how to add a __cmp__ method to override the relational and equality comparison operators to compare two Card objects
Demonstrates composition by creating a Deck class made up of Card objects
Adds a shuffle method to the Deck class
Adds various other methods to the Deck class to make it easy for a client card-playing program to use
Shows how to create a new class by inheriting from an existing class
Demonstrates how to override a method from the parent class when creating a new child class with inheritance
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
Shows how to import the cardGame module and, with inheritance, create a new class OldMaidHand
The complete simulation of Old Maid

Graphics with Python

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