Skip to content. | Skip to navigation

Personal tools
You are here: Home Computer Programming for Kids Python Accelerated Class Notes

Python Accelerated Class Notes

These are notes from an accelerated Python class I gave to a small group a few years ago. They are not designed to be used without the lectures, but perhaps they will be of use to some of you.

Homework 2 Answers

1. Write an expression to produce the integers between 1 and 10, inclusive

range(1,11)

2. Write a program to ask for a temperature in farenheit, and then display the temperature in celcius, to two decimal places

tempF = float(raw_input('Enter a temperature in fahrenheit: '))
tempC = (tempF - 32) * 5 / 9
print 'In celcius, that temperature is %.2f' % tempC

3. Write a program to ask for a number greater than -10, and to keep asking for it if the user enters something not greater than -10.

while 1:
    num = float(raw_input('Enter a number > -10: '))
    if num > -10:
        break

4. Write a program that prompts you for real numbers, one at a time, until you enter a 0, and then displays the sum of the numbers, rounded to 3 decimal places.

sum = 0.0
while 1:
    num = float(raw_input('Enter a real number: '))
    if num == 0:
        break
    sum += num
print '%.3f' % sum

Lesson 2

Computer Programming with Dave Briccetti
Wed, Feb 18, 2004
Introduction to Python
Concise Notes

Topics:
1) Functions
2) Exceptions
3) Classes
4) GUI

FUNCTIONS

Example 1:
def showIntro():
    print "This is the exciting introduction ..."

showIntro()

Example 2:
def addNumbers(num1, num2):
    return num1 + num2

sum = addNumbers(3,4)
print sum

Problem 1:
Write a program with a function which prompts the user for a
float, and returns it.

EXCEPTIONS

Example 3:
try:
    num = float(raw_input('Give us a number: '))
except ValueError:
    print 'Bad number'

Problem 2:
Prompt for two numbers. Display the result of dividing the first
number by the second. Prevent the program from "crashing" when
the divisor is 0.

CLASSES

Example 4:
class Robot:
    def workOn(self, task):
        print 'I am working on', task

robot = Robot()
robot.workOn('welding')

Problem 3:
Create a class called Calculator. Give it functions add, multiply
and divide. Handle a divide by 0 error.

GUI

Example 5:
from Tkinter import *

class Application(Frame):
    def createWidgets(self):
        self.quitButton = Button(self, text = 'Quit', command = self.quit)
        self.quitButton.pack()
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

app = Application()
app.mainloop()

Example 6:
from Tkinter import *

class Application(Frame):
    def greet(self):
        if self.formal.get():
            self.greeting.set('Hello. How are you?')
        else:
            self.greeting.set("What's up?")

    def createWidgets(self):
        self.formal = IntVar()
        self.button = Checkbutton(self, text = 'Formal', variable = self.formal)
        self.button.grid(row = 1, column = 1, columnspan = 2)
       
        self.greeting = StringVar()
        self.greetingLabel = Label(self, textvariable = self.greeting)
        self.greetingLabel.grid(row = 2, column = 1, columnspan = 2)
       
        self.quitButton = Button(self, text = 'Quit', command = self.quit)
        self.quitButton.grid(row = 3, column = 1, padx = 5, pady = 5)

        self.greetMeButton = Button(self, text = "Greet Me", command = self.greet)
        self.greetMeButton.grid(row = 3, column = 2, padx = 5)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.grid()
        self.createWidgets()

app = Application()
app.master.title("My Cool Application")
app.mainloop()

Homework 3

Due Tues, Mar 2, 5pm (email to daveb@davebsoft.com, all in a single email with no attachments)

1. Considering what you've learned recently, say what is wrong with this program:

num1 = float(raw_input('Please enter a number: '))
if num1 < 0:
    num1 *= 2
else:
    num1 *= 3

num2 = float(raw_input('Please enter a number: '))
if num2 < 0:
    num2 *= 2
else:
    num2 *= 3

print 'The result is', num1 + num2


2. Rewrite the program in problem 1 to correct the most serious flaw.

3. Write a function, getSpecialNum, to prompt for, and retrieve from the user, a number greater than 10. Here is what it might look like when you run it:

Enter a number > 10: x
That is not a number
Enter a number > 10: 10
That is not > 10
Enter a number > 10: 10.1
Thank you

4. Why might it be useful to know how to write functions like that?

5. Change your program from problem 3 so that the function is part of a class called InputCollector. To test the function, use the following code:

inputCollector = InputCollector()
inputCollector.getSpecialNum()

6. Read pages 3-5 of http://www.nmt.edu/tcc/help/pubs/tkinter.pdf

What does a geometry manager do?

7. Look at this page:

http://www.computerhistory.org/exhibits/highlights/alto.page

Prepare a 30-60 second oral presentation on something related to this page. Learn the material thoroughly, and present from brief notes. The notes should remind you of key points you want to talk about. Come to class with your notes, fully prepared and ready to deliver the presentation in 30-60 seconds.

Those of you who didn't deliver the last assigned presentation will be doing that one as well.

Homework 3 Answers

1. The program has a block of almost identical code which is repeated. It should
be "factored out" and put in a function.

2.

def getNum():
    num = float(raw_input('Please enter a number: '))
    if num < 0:
        num *= 2
    else:
        num *= 3
    return num

num1 = getNum()
num2 = getNum()

print 'The result is', num1 + num2


3.

def getSpecialNum():
    while 1:
        try:
            num = float(raw_input('Enter a number > 10: '))
            if num > 10:
                break
           
            print 'That is not > 10'
               
        except (ValueError):
            print 'That is not a number'

    print 'Thank you'

getSpecialNum()

4. You might need to use such functionality from several places in your program.

5.

class InputCollector:
    def getSpecialNum(self):
        while 1:
            try:
                num = float(raw_input('Enter a number > 10: '))
                if num > 10:
                    break
               
                print 'That is not > 10'
                   
            except (ValueError):
                print 'That is not a number'
   
        print 'Thank you'

inputCollector = InputCollector()
inputCollector.getSpecialNum()


6. A geometry manager arranges user interface components.

Lesson 3

Topics:
1) Lists
2) Dictionaries
3) Applications of previous topics

LISTS

Creating a list:
l = list() or l = [] or l = [1,2,3] or l = ['rice', 'butter']

Adding to a list:
l.append('soup')

Seeing if an element is in a list:
if 'rice' in l:

Accessing the elements of a list:
for item in l:

Problem 1:
Write a program with a list, which prompts for words until an
empty word is entered. For each word:

If it is already in the list, display a message to that effect
Otherwise add it to the list

Finally, display the list.

Problem 2:
Write a program to prompt for a series of numbers and store them in a list. For each element in the list, prompt the user for a number to add to the first. Store the sums in a second list. At the end display the second list.

DICTIONARIES

Creating a dictionary:
d = dict() or d = {} or d = {'dave': 20, 'eric': 25}

Adding:
d['sam'] = 30

Displaying all the keys:
d.keys()

Displaying all the values:
d.values()

Seeing if a key 'rice' is in a list:
if 'rice' in d:

Problem 3:
Write a word counting program with a dictionary, which prompts for words until an empty word is entered. For each word:

If it is not in the dictionary, add an element with the word as the key, and 1 as the value.
Else increment the value of the element with the word

Finally, display the dictionary, display just the keys, and
display just the values.

APPLICATIONS OF PREVIOUS TOPICS

Problem 4:
Create one or more programs of your own design, to apply elements of Pyton that you have learned.

Homework 3.5

Due Tues, Mar 16, 5pm (email to daveb@davebsoft.com, all in a single email with no attachments)
Late homework will not be accepted.

1. Write a program to prompt for strings and store them in a list. Shuffle the list and display it in its new order.

2. Create two class rosters (lists) of student names, by prompting for all the names.

Have the program display both rosters, and then display the names of any students who are in both classes. Use this approach: Loop over the elements of the first list, and see if each is also in the second list. If it is, display it.

Here's the output from my solution:

----------------------
Math class
Enter names, one per line. Give an empty name when done.
==> dave
==> sue
==> tim
==>
English class
Enter names, one per line. Give an empty name when done.
==> sue
==> steve
==> pete
==>
Math class: ['dave', 'sue', 'tim']
English class: ['sue', 'steve', 'pete']
In both classes:
sue
----------------------

My solution uses a function to fetch the list of names. Extra credit if yours does.

3. Practice your presention(s)

Homework 3.5 Answers

1. Write a program to prompt for strings and store them in a list. Shuffle the list and display it in its new order.

import random
strings = []

while 1:
    s = raw_input("Give us a string, gov. ")
    if s == "":
        break
    strings.append(s);

random.shuffle(strings)
print "Here are your strings, all nice and shuffled: ", strings

2. Create two class rosters (lists) of student names, by prompting for all the names.

Have the program display both rosters, and then display the names of any students who are in both classes. Use this approach: Loop over the elements of the first list, and see if each is also in the second list. If it is, display it.

Here's the output from my solution:

----------------------
Math class
Enter names, one per line. Give an empty name when done.
==> dave
==> sue
==> tim
==>
English class
Enter names, one per line. Give an empty name when done.
==> sue
==> steve
==> pete
==>
Math class: ['dave', 'sue', 'tim']
English class: ['sue', 'steve', 'pete']
In both classes:
sue
----------------------

My solution uses a function to fetch the list of names. Extra credit if yours does.

def getRoster():
    roster = []
    print 'Enter names, one per line. Give an empty name when done.'
    while 1:
        name = raw_input('==> ')
        if name == "":
            break
        roster.append(name)
    return roster

print 'Math class'
mathRoster = getRoster()
print 'English class'
englishRoster = getRoster()

print 'Math class:', mathRoster
print 'English class:', englishRoster

print 'In both classes:'

for name in mathRoster:
    if name in englishRoster:
        print name

Homework 4

Due Tues, Apr 6, 5pm (email to daveb@davebsoft.com, all in a single email with no attachments)
Late homework will not be accepted.

1. Write a program to do this:

Prompt for a series of game character names and magical power values. Use a dictionary to store the data. The character name is the key, and the magical power is the value. Display the names of the characters with magic over 80.

Here's a sample run of my solution:

Player name? Hemoglobin the Great Oxygenator
Magic power value? 90
Player name? Mitochondrion the Metabolizer
Magic power value? 75
Player name?
These characters have magic power values over 80:
Hemoglobin the Great Oxygenator

2. Find the equivalent of Python dictionaries in one or more of these other languages: Perl, C++, Java. Describe it briefly. Hint: this type of data structure is also known as an associative array, hash, or map.

Useful websites:

http://java.sun.com/docs/books/tutorial/collections/index.html
http://www.perl.com/pub/a/2000/10/begperl1.html

3. Why do you think I had you do the exercise in problem 2?

Computer Programming with Dave Briccetti
Wed, Mar 17, 2004, Introduction to Python, Concise Notes
Lesson 4

Topics:
1) Dictionaries
2) Applications of previous topics

DICTIONARIES

Creating a dictionary:
d = dict() or d = {} or d = {'dave': 20, 'eric': 25}

Adding:
d['sam'] = 30

Displaying all the keys:
d.keys()

Displaying all the values:
d.values()

Seeing if a key 'rice' is in a list:
if 'rice' in d:

Problem 1:
Write a word counting program with a dictionary, which prompts for words until an empty word is entered. For each word:

If it is not in the dictionary, add an element with the word as the key, and 1 as the value.
Else increment the value of the element with the word

Finally, display the dictionary, display just the keys, and
display just the values.

APPLICATIONS OF PREVIOUS TOPICS

Problem 2:
Create one or more programs of your own design, to apply elements of Python that you have learned.

Lesson 5 Program

I've made some small improvements. Rather than each place being a list of three elements (which is hard to read with all the place[0] and so on), I made each place an object of the Place class.

class Place:

    def __init__(self, desc, targets, objects):
        self.desc = desc
        self.targets = targets
        self.objects = objects

    def show(self):
        print place.desc
        self.showObjects()
        self.showTargets()

    def showObjects(self):
        if self.objects:
            print 'These objects are here:'
            for object in self.objects:
                print "\t", object

    def showTargets(self):
        if self.targets:
            print 'From here you can go to: '
            for target in self.targets:
                print "\t", target

def showItems():
    if collectedItems:
        print 'You have collected these items:'
        for item in collectedItems:
            print "\t", item

places = {}
collectedItems = []

places["forest"] = Place(
    "You are in the middle of a dark forest. Strange creatures howl in the distance.",
    ("airstrip", "waterfall"),
    ["acorn", "codebook", "bicycle"]
    )
places["airstrip"] = Place(
    "You are at the airstrip. The place is covered with weeds.",
    ("forest",),
    ["propeller"]
    )
places["waterfall"] = Place(
    "The waterfall makes a deafening sound.",
    ("forest",),
    ["fish"]
    )

place = places["forest"]

while 1:
    place.show()
    showItems()
    cmdLine = raw_input('--> ')
    cmdWords = cmdLine.split(' ')
    cmd = cmdWords[0]
    cmdArgs = cmdWords[1]
    availPlaces = place.targets
    availItems = place.objects

    if cmd == 'go':
        newPlace = cmdArgs
        if newPlace in availPlaces:
            place = places[newPlace]
        else:
            print 'You can\'t go there.'
    elif cmd == 'get':
        requestedItem = cmdArgs
        if requestedItem in availItems and not (cmdArgs in collectedItems):
            collectedItems.append(requestedItem)

Homework 5

Due Tues, Apr 20, 5pm (email to daveb@davebsoft.com).

Using the 4/12 version of Program 5 as a model, if you like, create a text adventure game (or other game--see below) which:

1: Uses at least one class
2: Uses a variety of interesting data structures (lists, tuples, dictionaries, and the like)

3 (Super-extra credit): Use XML to encode the game world information
4 (Super-extra credit): Use Tkinter to have the game running in a window

We will have walkthroughs of your code in class. You will explain the code, and your classmates and I will make positively-phrased suggestions to help you improve your code.

You don't have to create a text adventure game. Any type of game that gives you practice working on classes and data structures is fine.

Homework 6, Due Tue, May 4, 5 PM

1) Install PyXml from http://pyxml.sourceforge.net/topics/
2) Get my game version 4, http://www.davebsoft.com/Teaching/Classes/Python/examples/adventure4.zip, and make sure it runs
3) Read this Introduction to XML, including the four subsections: http://pyxml.sourceforge.net/topics/howto/section-introduction.html
4) Read Section 6, http://pyxml.sourceforge.net/topics/howto/section-DOM.html, including 6.1 and 6.5
5) Using my adventure4/game.xml as an example, create an xml file for your game, and put one scene in it. Email it to me, and when I approve it, you may add the rest of your scenes if you like.
6) For the two of you who failed to submit your last homework:  Prepare a one-minute presentation on either:
a) The IBM 360 computer
b) Magnetic drum storage
c) The origins of the Java language
You will deliver it on May 5th.

Have fun learning XML. It's very widely used these days, and is good to know about.

Homework 7

Create an XML file containing a pretend list of robot parts (motor, sensor, wheel, battery, etc.) and their prices. Read the data into a dictionary. Prompt the user for the name of a part, and display the price after looking it up in the dictionary. Ask me, or each other, for help if you need it.

Rank at least three of the following, in the order in which you would be interested in learning about them (most interesting first):

Doing web sites with Python
Doing web sites with Perl
Doing web sites with PHP
Using databases from scripting languages (such as Python)
GUIs with Python
Network programming with Python
PyGame
C++
Java

Two of you will be giving presentations.


Computer Programming with Dave Briccetti
Wed, May 5, 2004, Introduction to Python, Concise Notes
Lesson 7

Outline

1) XML
2) More from Lesson 6 if time permits


from xml.dom.ext.reader.Sax import FromXmlFile
from xml.dom.NodeFilter import NodeFilter

root = FromXmlFile('problem1.xml')

walker = root.createTreeWalker(root.documentElement,
                              NodeFilter.SHOW_ELEMENT, None, 0)

while 1:
    nodeName = walker.currentNode.nodeName

    if nodeName == 'game':
        print "Hey, I found the game tag!"
       
    next = walker.nextNode()
   
    if next is None: break

-----

<game>
</game>

-----

from xml.dom.ext.reader.Sax import FromXmlFile
from xml.dom.NodeFilter import NodeFilter

root = FromXmlFile('problem2.xml')
walker = root.createTreeWalker(root.documentElement,
                              NodeFilter.SHOW_ELEMENT, None, 0)

while 1:
    print walker.currentNode
    print walker.currentNode.attributes
    next = walker.nextNode()
    if next is None: break

-----

<game title='Fun With Scissors'>
<player name='Jim'/>
<player name='Sue'/>
</game>

Lesson 8
Sample CGI Python program which prompts for a name, and then displays it

#!c:\python23\python.exe
import cgi
import cgitb
cgitb.enable()
print "Content-type: text/html\n\n"

form = cgi.FieldStorage()
if form.has_key('robotName'):
    print form["robotName"].value + " is a great name"
else:
    print """
<html>
<form>
What is your robot's name?
<input name='robotName'>
<input type='submit'>
</form>
</html>
    """

Homework 8
Due June 1, 2004, 5 PM

Do 0 or more of the following:

1) Install Apache Web Server (www.apache.org) and get the Lesson 8 sample running

2) Read about CGI with Python: http://python.org/doc/lib/module-cgi.html

3) Get more experience with XML and Python

4) Review all the class notes on TKinter


Related content