2

If you bind GUI event to a function you use a callback function, alas, callback functions are not allowed to have arguments. To remedy situation you can use currying or lambda. Here is an examples of both:

# currying allows GUI callback functions to have arguments
# an alternative is lambda

from Tkinter import *

class Curry:
    """adds arguments to callback function"""
    def __init__(self, callback, *args, **kwargs):
        self.callback = callback
        self.args = args
        self.kwargs = kwargs

    def __call__(self):
        # needs Python23 or higher
        return self.callback(*self.args, **self.kwargs)

def callback(what=None):
    print "callback =", what  # for testing
    if what == 'red':
        b1.config(bg="#ff0000")
    if what == 'blue':
        b2.config(bg="#0000ff")

root = Tk()

# uses class Curry, since command=callback("red") will not work
b1 = Button(root, text="red", width=6, command=Curry(callback, "red"))
b1.pack(side=LEFT, padx=2, pady=2)

# uses lambda instead of Curry
b2 = Button(root, text="blue", width=6, command=lambda: callback("blue"))
b2.pack(side=LEFT, padx=2, pady=2)

mainloop()

Editor's Note:
command uses a function object rather then a function call, so arguments have to be added with a lambda or curry wrapper.

1

The Python module threading allows you to run a function in the background, as your main program executes. This example adds another feature of Python, called function decoration, the @decorator is added to just above the function you want to run in the background, as example shows:

# running a function in the background with threading
# (apply threading to a function with a function @decorator)

import time
import threading

def background(f):
    def bg_f(*a, **kw):
        threading.Thread(target=f, args=a, kwargs=kw).start()
    return bg_f

# the @decorator forces this function to run in the background
@background
def counter(n):
    i = 0
    while i < n:
        print i
        i += 1
        time.sleep(0.5)  # 0.5 second delay

counter(7)
time.sleep(0.4)
print 'hello'   # prints hello, before counter prints 1 ...
time.sleep(1.2)
print 'world'   # prints world, before counter prints 4 ...

Output looks like:

0
hello
1
2
3
world
4
5
6
0

Here is an example of how you could use Tkinter, a loop, counter, and some other stuff. Here is the program code:

#Created by Mattamus Prime (AKA Matt Tacular)
#This is a simple dice program, pretends to roll a die and show you the progress
#After 25 random screens, it picks one to show.

import random
from Tkinter import *
import time

def clear():
    answerLabel2.configure(text="")
    answerLabel3.configure(text="")
    answerLabel4.configure(text="")
    mainWindow.update()
    
def aDie():
    infiniteLoop = True
    counter = 0
    while infiniteLoop:
        number = random.randint(1,6)
        time.sleep(0.1)
        clear()
        counter += 1
        if number == 1:
            strDie2 = "I              I"
            strDie3 = "I      II      I"
            strDie4 = "I              I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 2:
            strDie2 = "I    II        I"
            strDie3 = "I              I"
            strDie4 = "I        II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 3:
            strDie2 = "I        II    I"
            strDie3 = "I      II      I"
            strDie4 = "I    II        I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 4:
            strDie2 = "I    II  II    I"
            strDie3 = "I              I"
            strDie4 = "I    II  II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 5:
            strDie2 = "I    II  II    I"
            strDie3 = "I      II      I"
            strDie4 = "I    II  II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        elif number == 6:
            strDie2 = "I    II  II    I"
            strDie3 = "I    II  II    I"
            strDie4 = "I    II  II    I"
            answerLabel2.configure(text=strDie2)
            answerLabel3.configure(text=strDie3)
            answerLabel4.configure(text=strDie4)
            number = random.randint(1,6)
        if counter == 25:
            break
        mainWindow.update()
mainWindow = Tk()
    
startButton = Button(mainWindow, text="Roll", command=aDie, width=20)
startButton.grid(row=0, column=0)

answerLabel = Label(mainWindow, text="IIIIIIIIIIIIIIII", width=20)
answerLabel.grid(row=1, column=0)

answerLabel2 = Label(mainWindow, text="I              I", width=20)
answerLabel2.grid(row=2, column=0)

answerLabel3 = Label(mainWindow, text="I              I", width=20)
answerLabel3.grid(row=3, column=0)

answerLabel4 = Label(mainWindow, text="I              I", width=20)
answerLabel4.grid(row=4, column=0)

answerLabel5 = Label(mainWindow, text="IIIIIIIIIIIIIIII", width=20)
answerLabel5.grid(row=5, column=0)

mainWindow.mainloop()

What I did, was made a window in Tkinter and in that window made a "Roll" Button. then there are 5 blank labels that get filled by different lines of IIII's depending on what number from 1 - 6 is chosen.

This also shows how you can set up a loop that only ends when the counter hits a certain number, and that only happens when the die has displayed a certain amount of numbers.

And if you want it to run the window with no console, save the code as "filename.pyw" instead of "filename.py"

4

You have seen those animated GIF files on webpages, wiggling and jiggling, sometimes fun, sometimes annoyance. I wanted an animated GIF file to animate on Tkinter, but only got a still picture.

An animated GIF file is really just a series of GIF files, like a series of frames in a movie. You can take one of the common GIF Animator Utlities and extract the individual GIF files that make up the series.

Next, loop these image files through the regular canvas.create_image() function, delay each frame to mimic animation, and you have your custom made movie. Here is the code example ...

# mimic an animated GIF displaying a series of GIFs
# (an animated GIF was used to create the series of GIFs with a common GIF animator utility)
 
import time
from Tkinter import *
 
root = Tk()
 
imagelist = ["dog001.gif","dog002.gif","dog003.gif","dog004.gif","dog005.gif","dog006.gif","dog007.gif"]
 
# extract width and height info
photo1 = PhotoImage(file=imagelist[0])
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
 
# loop through the series of GIFs
for k in range(0, 1000):
    print imagelist[k%7], k # test only
    photo1 = PhotoImage(file=imagelist[k%7])
    canvas1.create_image(width1/2.0, height1/2.0, image=photo1)
    canvas1.update()
    time.sleep(0.1)
 
root.mainloop()

I have attached a small zip file containing the set of individual pictures that make up the animated GIF.

1

Display the letters in a text sorted by their frequency of occurance:

import string
 
# create a list of lower case letters
# ['a', 'b', 'c', 'd', 'e', ... ]
alpha_list = list(string.lowercase)
 
text = """The Spell Checker Poem ...
 
Eye halve a spelling chequer
It came with my pea sea
It plainly marques four my revue
Miss steaks eye kin knot sea.
 
Eye strike a key and type a word
And weight four it two say
Weather eye am wrong oar write
It shows me strait a weigh.
As soon as a mist ache is maid
It nose bee fore two long
And eye can put the error rite
Its rare lea ever wrong.
 
Eye have run this poem threw it
I am shore your pleased two no
its letter perfect awl the weigh
My chequer tolled me sew.
"""
 
# convert text to all lower case letters
text = text.lower()
 
# create a list of (frequency, letter) tuples
tuple_list = []
for letter in alpha_list:
    tuple_list.append((text.count(letter), letter))
 
# sort by frequency (high value first)
tuple_list.sort(reverse=True)
#print tuple_list
 
# show all letters with frequency above 0
for freq, letter in tuple_list:
    if freq > 0:
        print letter, freq
 
"""
result =
e 67
t 33
a 32
r 29
s 26
...
 
"""

Moderator's note: php tags didn't work properly, replaced them.

1

This short code finds all files in a given drive or folder/directory that end with a selected file extension. It also checks all the subdirectories:

import os
 
# pick a folder or drive
folder = 'C:\\'
# pick a file extension
extension = ".css"
 
print "All files in %s ending with %s :" % (folder, extension)
file_list = []
for (paths, dirs, files) in os.walk(folder):
    for file in files:
        if file.endswith(extension):
            # show progress
            print '.',
            file_list.append(os.path.join(paths, file))
 
print
 
for full_filename in file_list:
    print full_filename
2

If you want to create a unique filename in a given folder use the Python module tempfile:

import tempfile

# creates a random file (text=True is textfile, text=False is binary file)
ext = '.txt'
pfx = 'tmp'
dir = 'C:\\Temp'
filename = tempfile.mkstemp(suffix=ext, prefix=pfx, dir=dir, text=True)[1]
print filename  # eg. C:\Temp\tmpsnrfgk.txt

# test it ...
fout = open(filename, 'w')
fout.write("Just a text file")
fout.close()
2

So, you want to know the operating system your computer has? This short Python code can tell you:

import sys

operating_system = sys.platform
print operating_system              # eg.  win32

if operating_system[:3] == 'win':
    print "Your OS is Windows"
elif operating_system[:5] == 'linux':
    print "Your OS is Linux"

# or ........

import os

print os.name              # eg.  nt
print os.environ['OS']   # eg.  Windows_NT
3

This code allows you to create unique file names containing date and time that can be sorted by age:

import time

# using year_month_day_hour_min_sec  (24 hour foemat)
filename1 = time.strftime('%Y_%m_%d_%H_%M_%S.dat')
print filename1  # eg.   2006_08_05_20_57_56.dat

# or using seconds since epoch
filename2 = str(int(time.time())) + ".dat"
print filename2  # eg.  1154825876.dat
1

Version 2.5 of Python final release is planned for 12sep2006. It will have a few nice improvements. On of them is class partial. Bumsfeld has talked about adding arguments to GUI callback functions earlier. This new class will help. Here is a fun example that can be used with Python 2.4:

# class partial is similar to currying to add arguments
# starting with Python 2.5 you can simply import class partial
# using: from functools import partial

from Tkinter import Tk, Canvas, Button


class partial(object):
    """partial application using both positional and keyword arguments"""
    def __init__(*args, **kw):
        self = args[0]
        self.fn, self.args, self.kw = (args[1], args[2:], kw)

    def __call__(self, *args, **kw):
        if kw and self.kw:
            d = self.kw.copy()
            d.update(kw)
        else:
            d = kw or self.kw
        return self.fn(*(self.args + args), **d)


root = Tk()
c = Canvas(root,width=200,height=50)
c.pack()

color_list = ['red','blue','green','yellow','black','white']
for color in color_list:
    # uses class partial to construct callbacks for Tkinter widgets
    # called as though it were a function
    # basically passes/implements c.config(bg=color)
    b = Button(root, text=color, command=partial(c.config, bg=color))
    b.pack(side='left')

root.mainloop()

Edit: A correction has been made, in the final production release of Python 2.5 partial() is in module functools.

3

Just a few odd things you can do with lists in Python ...

# create a list of char 'a' to 'z'
list_a2z = map(chr, range(ord('a'), ord('z')))
print list_a2z
 
# create a list of char using a generator expression
char_list = list(x for x in "abcd")
print char_list # ['a', 'b', 'c', 'd']
 
# create an enumerated char list
enumchar_list = list(enumerate('abcd'))
print enumchar_list  # [(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd')]
 
# can be easily changed to a dictionary
dict1 = dict(enumchar_list)  
print dict1  # {0: 'a', 1: 'b', 2: 'c', 3: 'd'}
# swap key:value of dictionary
dict2 = dict([(v, k) for (k, v) in dict1.iteritems()])
print dict2  # {'a': 0, 'c': 2, 'b': 1, 'd': 3}
 
print
 
x = [1, 2, 3, 4]
# create a listreverseiterator object, leaves the source unchanged
# reversed() needs Python24 and higher
rx = reversed(x)
print rx        # <listreverseiterator object at 0x00AE2D70>
print "original list:"
print x
print "reversed list:"
print list(rx)  # [4, 3, 2, 1]
 
print
 
# reset the iterator object and iterate
rx = reversed(x)
for k in rx: 
    print k,    # 4 3 2 1
print
 
print
 
# create a list with duplicate items/elements
list1 = list(x for x in "abcdefab")
print list1  # ['a', 'b', 'c', 'd', 'e', 'f', 'a', 'b']
 
print
 
# weed out duplicate items from this list via list comprehension
list2 = []
# translation: add item from list1 to list2 if it's not there

[list2.append(item) for item in list1 if not list2.count(item)]
print list2  # ['a', 'b', 'c', 'd', 'e', 'f']
 
print
 
# same but using a set, this will change order
# set uses a hashed order
set1 = set(list1)
print set1        # set(['a', 'c', 'b', 'e', 'd', 'f'])
print list(set1)  # ['a', 'c', 'b', 'e', 'd', 'f']
 
print
 
# working with a nested lists
list3 = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]
 
print list3[1]        # Dick
print list3[3]        # ['Mary', 7, 9, [700, 777]]
print list3[3][0]     # Mary
print list3[3][3]     # [700, 777]
print list3[3][3][1]  # 777
 
# make a shallow copy of list 3
list4 = list(list3)  # or list4 = list3[:]
print list3
print list4
 
# change Dick to Mike in list3
list3[1] = 'Mike'
# test it ...
print list3  # [1, 'Mike', 2, ['Mary', 7, 9, [700, 777]], 13]
print list4  # [1, 'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]  okay!
 
# change the more nested Mary to Sue in list3
list3[3][0] = 'Sue'
# test it ...
print list3  # [1, 'Mike', 2, ['Sue', 7, 9, [700, 777]], 13]
print list4  # [1, 'Dick', 2, ['Sue', 7, 9, [700, 777]], 13]  oops!
 
# to make a true copy of a nested list use function deepcopy() from module copy
import copy
 
list5 = [1 ,'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]
list6 = copy.deepcopy(list5)
 
# change Mary to Sue in list5
list5[3][0] = 'Sue'
# test it ...
print list5  # [1, 'Dick', 2, ['Sue', 7, 9, [700, 777]], 13]
print list6  # [1, 'Dick', 2, ['Mary', 7, 9, [700, 777]], 13]  that's better!
 
print
 
# make a list of ten zeroes
list7 =  [0] * 10
print list7  # [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
list7[0] = 77
print list7   # [77, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
# wonder what the result will be?
list8 = list7 * 2
print list8   # [77, 0, 0, 0, 0, 0, 0, 0, 0, 0, 77, 0, 0, 0, 0, 0, 0, 0, 0, 0]
 
print
 
def minmax4(lst, typ):
    """return min/max of mixed list lst for items of type typ"""
    temp = [x for x in lst if isinstance(x, typ)]
    return min(temp), max(temp)
 
# minmax4() test ...
mixed_list = [11, 'Dick', 12, 'Mary', 7, 'Zoe', 9, 700, 777, 'Paul', 13456789]
print mixed_list
 
print "The min and max of the integers are:"
mn, mx = minmax4(mixed_list, int)
print "minimum = %s  maximum = %s" % (mn, mx)
 
print "The min and max of the strings are:"
mn, mx = minmax4(mixed_list, str)
print "minimum = %s  maximum = %s" % (mn, mx)
 
"""
minmax4() test -->
[11, 'Dick', 12, 'Mary', 7, 'Zoe', 9, 700, 777, 'Paul', 13456789]
The min and max of the integers are:
minimum = 7  maximum = 13456789
The min and max of the strings are:
minimum = Dick  maximum = Zoe
"""

Note: the code field is for php, but it gives some color to Python code. Vanity on my part!
Note+: php tags don't work any longer, don't use them, eat crow!

Edited by vegaseat: [code=python] tag

0

There are situations where you want to add s to string to indicate plural. Here is example:

print "<%s>" % ('s' * 0)  # <>
print "<%s>" % ('s' * 1)  # <s>
print 1 != 1              # False --> 0
print 2 != 1              # True --> 1

# add an 's' to indicate plural when k is not 1
for k in range(1, 4):
    print "The for loop ran %d time%s" % (k, 's'*(k != 1))

"""
The for loop ran 1 time
The for loop ran 2 times
The for loop ran 3 times
"""
0

If you get confused with the builtin functions input() and raw_input() (Who came up with raw_input anyway?), you can change the names of these functions in your program to something you understand better:

input_str = raw_input
input_int = input
# now you can use ...
name = input_str("Enter your name: ")
age = input_int("Enter your age: ")

print "Hi %s, you are %d old!" % (name, age)
# or if this is more readable use this ...
print "Hi %(name)s, you are %(age)d old!" % vars()
2

This short function tells you if the items in a given list are unique (no duplicates) ...

# are the items in a list unique:
def is_list_unique(list1):
    """are the items in list1 unique, returns True or False"""
    return len(list1) == len(set(list1))
 
list1 = [1, 2, 3, 4, 5]
print is_list_unique(list1)  # True
 
list2 = [1, 2, 3, 3, 4, 5]
print is_list_unique(list2)  # False
0

Ever wanted to make a text adventure? It's quite simple:

#First you define the start of the game:
def game_start():
    print '''Your story opening here'''
    room1() #takes you to the function room 1, when you have 
    #defined it.
 
def room1():
    """This code will print a description of your room1,
    say, the foyer of a house."""
    room1_prompt() #You will take the user to the prompt
 
def room1_desc():
    """The description here is called every time a command such as
    'look' is typed into the prompt."""
   room1_prompt()
 
def room1_prompt():
    """Here, you will take input to determine what will happen. You
    sort all the problems with an if-elif-else loop."""
    promptR1 = raw_input("Type a command: ").lower() 
# The .lower
#will convert the user input all to one case, so that it is
#interpreted as:
#Look.lower() == look == "look"
 
    if promptR1 == "look":
        room1_desc()
    elif promptR1 == "help":
#defined function for help, to print a list of commands
    else:
       print "That is invalid"
       room1_prompt()

This code will create a room in three functions, one to load the room and give a description; the prompt, which acts as a hub from which all other commands are reached. Each room shares a help statement, but where you go or what you can look at is all done in the prompts.

I hope that this helped, I'm new at this language too, but I'm making a text adventure so I know hat I'm on about! :P

2

Do you want to check if two files are equal? Easy with Python module filecmp ...

# compare two files and check if they are equal
# files can be binary or text based
import filecmp
 
# pick two files you want to compare ...
file1 = "Boing1.wav"
file2 = "Boing2.wav"
if filecmp.cmp(file1, file2):
    print "Files %s and %s are identical" % (file1, file2)
else:
    print "Files %s and %s differ!" % (file1, file2)
0

A short Python code to show you how to create a card game. Unzip the attached card image file into a directory that you want the program to use.

The code shows you how to create a list of card names which match the filenames of the images (+.gif), shuffle the list, pick a hand of five cards, and display the cards in a Tkinter GUI. The image objects are stored indexed by card name in a dictionary ...

# using Tkinter to display a hand of 5 random card images
# each time you click the canvas
# (images are in GIF format for Tkinter to display properly)
 
from Tkinter import *
import random
 
root = Tk()
root.title("Click me!")
 
def create_cards():
    """
    create a list of 52 cards
    suit: club=C, diamond=D, heart=H spade=S
    rank: ace=A, 10=T, jack=J, queen=Q, king=K, numbers=2..9
    ace of spade would be SA, 8 of heart would be H8 and so on ...
    """
    return [ suit + rank for suit in "CDHS" for rank in "A23456789TJQK" ]
 
def shuffle_cards(card_list):
    """random shuffle a list of cards"""
    # make a copy of the original list
    card_list1 = card_list[:]
    random.shuffle(card_list1)
    return card_list1
 
def pick_5cards(card_list):
    """pick five cards from the shuffled list"""
    return card_list[:5]
 
def create_images():
    """create all card images as a card_name:image_object dictionary"""
    card_list = create_cards()
    image_dict = {}
    for card in card_list:
        # all images have filenames the match the card_list names + extension .gif
        image_dict[card] = PhotoImage(file=image_dir+card+".gif")
        #print image_dir+card+".gif"  # test
    return image_dict
 
def next_hand(event):
    """create the card list, shuffle, pick five cards and display them"""
    card_list = create_cards()
    card_list = shuffle_cards(card_list)
    card_list = pick_5cards(card_list)
    root.title(card_list)  # test
 
    # now display the card images at the proper location on the canvas
    x = 10
    y = 10
    for card in card_list:
        #print card, x, y  # test
        canvas1.create_image(x, y, image=image_dict[card], anchor=NW)
        # calculate each NW corner x, y
        x += 90
 
# change this to the directory your card GIFs are in
image_dir = "D:/Python24/Atest/images/Cards_gif/"
 
# load a sample card to get the size
photo1 = PhotoImage(file=image_dir+"C2.gif")
 
# make canvas 5 times the width of a card + 100
width1 = 5 * photo1.width() + 100
height1 = photo1.height() + 20
canvas1 = Canvas(width=width1, height=height1)
canvas1.pack()
 
# now load all card images into a dictionary
image_dict = create_images()
#print image_dict  # test
 
# bind left mouse click on canvas to next_hand display
canvas1.bind('<Button-1>', next_hand)
 
root.mainloop()

From there you can expand the game to discard and replace selected cards and to analyze, if you have a poker hand.

Click on "Toggle Plain Text" so you can highlight and copy the code to your editor.

1

You have two similar lists and want to see what items are in list1 that are not in list2 and vice versa. The trick is to convert them into sets and take the difference:

color_list1 = ["red","green","blue","purple","yellow","violet","white","cyan",
   "magenta","turquoise","black","lightblue","grey","lightgrey","darkgrey",
   "lightgreen","teal","pink","darkblue","darkred","darkgreen","orchid","beige"]

color_list2 = ["red","green","blue","purple","yellow","orchid","grey","white",
   "cyan","magenta","turquoise","limegreen","lightblue","lightgrey","darkgrey",
   "lightgreen","tan","darkblue","darkred","darkgreen","violet","pink","beige"]

print "color_list1 =", color_list1
print "-"*70  # 70 dashes
print "color_list2 =", color_list2
print "-"*70

# convert lists to sets
color_set1 = set(color_list1)
color_set2 = set(color_list2)

print "These are the colors of color_list1 that are not in color_list2:"
print color_set1 - color_set2
print "-"*70

print "These are the colors of color_list2 that are not in color_list1:"
print color_set2 - color_set1
Votes + Comments
Good understanding of Python
0

Let's draw some colorful shapes on a Tkinter canvas and clear the canvas after a given amount of seconds:

# clear the Tkinter canvas after drawing some shapes

from Tkinter import *

root = Tk()
root.title("clear canvas after 5 seconds")

# create the canvas to draw upon
# default background color (bg) is "facecolor"
c = Canvas(root, width=500, height=420, bg="white")
c.pack()

# draw a maroon line from x1=10,y1=20 to x2=200,y2=100
# default width=1 and fill="black"
c.create_line(10, 20, 200, 100, width=2, fill="maroon")

# draw an ovel inside a box with corner coordinates x1=200,y1=20 and x2=450,y2=100
# fill the oval blue (if the box is square a circle is drawn)
c.create_oval(200, 20, 450, 100, fill="blue")

# draw a red rectangle with corner coordinates x1=50,y1=150 and x2=300,y2=400
c.create_rectangle(50, 150, 300, 400, fill="red")

# since the above rectangle is a square stuff a green circle in it
c.create_oval(50, 150, 300, 400, fill="green")

root.after(5000, c.delete, ALL)  # after 5000 ms call c.delete(ALL)

root.mainloop()
2

I know you have seen hints of this before, but you can use formatted print to display the key:value of a dictionary. Here is an example ...

# when you set up variables like ...
book = "Python for Nuts"
pages = 223
scripts = 77
 
# Python keeps this information in a local dictionary called up with vars()
print vars()  #  { ... , 'pages': 223, 'book': 'Python for Nuts', 'scripts': 77, ... }
 
# now you can show the results like this ...
print "%s has %s pages and contains a total of %s code examples" % (book, pages, scripts)
 
# or take advantage of vars() ...
print "%(book)s has %(pages)s pages and contains a total of %(scripts)s code examples" % vars()

Also note that %s can be used for strings and raw numbers.

1

The request came up on the forum for some typical Python class sample code. Here is my nickles worth:

# manage the contents of a basket
# note: 
#   "self" keeps track of instances, here basket1 and basket2
#   it has to be the first argument of a class method/function

class Basket(object):
    """
    a class to add elements to a list and display the result
    default is an empty basket
    """
    def __init__(self, contents=[]):
        # make a true copy of contents list to avoid surprises
        contents = contents[:]
        self.contents = contents

    def add(self, element):
        # add elements to the basket (list)
        self.contents.append(element)
    
    def remove(self, element):
        # remove an element from the basket
        if element in self.contents:
            self.contents.remove(element)
        else:
            print element, " not in basket!"
            
    def print_me(self):
        # print out the list elements as a string
        result = " ".join(self.contents)
        print "Basket now contains:", result


# basket1 instance of the class, it is an empty basket
basket1 = Basket()
# add items to basket1
basket1.add('pins')
basket1.add('needles')
basket1.add('wurst')

# basket2 instance starts out with contents of basket1
# and allows the user to add more elements
basket2 = Basket(basket1.contents)

basket1.print_me()
print "Add things to the basket, use -thing to remove it:"
while True:
    thing = raw_input("Enter a thing (press Enter only to exit): ")
    if thing:
        if thing[0] == '-':
            basket2.remove(thing[1:])
        else:
            basket2.add(thing)
        basket2.print_me()
    else:
        break
    
# final tally, show things now in basket2
print "Final tally:"
basket2.print_me()
1

Here is a simple linear equation solver:

# a Python linear equation solver

def solve(eq, var='x'):
    eq1 = eq.replace("=", "-(") + ")"
    #print eq1   # test
    c = eval(eq1, {var:1j})
    #print c     # test
    return -c.real/c.imag


eq = "x-2 = 2*x"  # example
r = solve(eq)
print "equation: %s\n  result: x = %s" % (eq, r)
1

Looking at Ene's Python class sample code, I realized that it would be nice to have a sample of class inheritance ...

# class Teacher and class Student inherit from class SchoolMember

# the base or super class
class SchoolMember(object):
    '''represents any school member'''
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def detail(self):
        '''show name and age, stay on same line (trailing comma)'''
        print 'Name: %-13s Age:%s' % (self.name, self.age),

# use the base class as argument to inherit from
class Teacher(SchoolMember):
    '''represents a teacher'''
    def __init__(self, name, age, subject):
        # call the base class constructor ...
        # it assigns name, age to self.name, self.age
        SchoolMember.__init__(self, name, age)
        self.subject = subject

    def detail(self):
        '''teaches this course'''
        SchoolMember.detail(self)
        print 'Teaches course: %s' % self.subject

class Student(SchoolMember):
    '''represents a student'''
    def __init__(self, name, age, grades):
        SchoolMember.__init__(self, name, age)
        self.grades = grades

    def detail(self):
        '''student grades'''
        SchoolMember.detail(self)
        print 'Average grades: %d' % self.grades

# teacher has name age and subject taught
t1 = Teacher('Mr. Schard', 40, 'Beginning Python 101')
# student has name, age and average grade (max 100)
s1 = Student('Abigale Agat', 20, 92)
s2 = Student('Bertha Belch', 22, 65)
s3 = Student('Karl Kuss', 21, 98)
s4 = Student('Tom Tippit', 22, 77)
s5 = Student('Zoe Zeller', 20, 88)

print '-'*55

# list of instances, Teacher t1 and Students s1 ... s5
members = [t1, s1, s2, s3, s4, s5]
sumgrades = 0
for member in members:
    memberType = member.detail()
    try:
        sumgrades += member.grades
    except AttributeError:
        pass # this would be a teacher, has no grades so skip
    
print "\n%s's students class-average grades = %d" % (t1.name, sumgrades/5)

"""
output =
Name: Mr. Schard    Age:40 Teaches course: Beginning Python 101
Name: Abigale Agat  Age:20 Average grades: 92
Name: Bertha Belch  Age:22 Average grades: 65
Name: Karl Kuss     Age:21 Average grades: 98
Name: Tom Tippit    Age:22 Average grades: 77
Name: Zoe Zeller    Age:20 Average grades: 88

Mr. Schard's students class-average grades = 84
"""
0

Import the module shutil, it has functions for copying and moving files, copying whole directory trees, deleting directory trees and more.

1

Some details on the use of modules in Python, heavily commented. Here is an example of a module:

# modules should be saved to the same folder as the 
# program or to folders listed in sys.path()

# save this module code as apple.py ...
# (module-name and file-name.py have to match, are case sensitive!)

def pieCookingStatus(cooking_time):
    if cooking_time < 35:
        print "Still cooking!"
    elif cooking_time < 40:
        print "Almost done!"
    else:
        print "Take pie out of the oven!"

def piePercentCooked(cooking_time):
    """consider 40 minutes the fully cooked time"""
    return 100 * cooking_time/40

# optional, specify version number of module
version = '1.2'

# this test runs when this code is used as a standalone program, 
# but not as an imported module of another program,
# then the namespace will be apple (name of module) and not __main__
if __name__ == '__main__':
    print "Pie is %d percent cooked." % piePercentCooked(33)
    pieCookingStatus(33)

Now the program that would use the above module:

# test the module apple.py

# import creates a namespace with the module's name (apple)
# also Python creates a precompiled bytecode file apple.pyc for speed
import apple

# optional, check version if it has been specified
if 'version' in dir(apple):
  print 'Version =', apple.version

# optional, show namespaces used
# note that namespace __name__ is assumed for this program
# you don't have to use it, but you have to prefix the 
# modules namespace to functions/variables of the module
# in this case prefix with apple and a dot
print "Namespace of program:", __name__        # __main__
print "Namespace of module :", apple.__name__  # apple

# also optional, list filenames used
print __file__         # C:/Python24/Atest/AppleTest.py
print apple.__file__   # C:/Python24/Atest/apple.pyc

# now let's do something with the apple module
minutes_cooking = 45
percent_cooked = apple.piePercentCooked(minutes_cooking)
print "Pie is %0.1f percent cooked." % percent_cooked
apple.pieCookingStatus(minutes_cooking)

If you have your module in a subdirectory of your own that is not on the PYTHONPATH then you can change the import statement:

"""
your program myprog.py may be in C:\Python24\myprog.py
the module is in C:\Python24\directory1\directory2\module1.py
C:\Python24\ would be listed in sys.path() (PYTHONPATH)
"""

# import modules from subfolders:
from directory1.directory2 import module1
1

Okay, with all that Administrator stuff out of the way let's return to the "Starting Python" sticky.

If you had a list of names with title, first, middle and last name, how would you sort that list by the last name only? Well here is a solution commonly used to sort lists by item or modified item:

# sort a list of names by last name

def sort_names(names):
    """
    sort names by last name, avoiding title, first and middle names
    """
    names_mod = []
    for name in names:
        # split each name into a list
        name_list = name.split()
        # pick the last name from list
        last_name = name_list[-1]
        # create a list of temporary sublists [last_name, name] 
        names_mod.append([last_name, name])
    # sort the modified list of names inplace
    # this will sort by the first item in the 
    # sublists which is last_name
    names_mod.sort()
    # use list comprehension to
    # to remove the temporary last_name item
    return [name[1] for name in names_mod]

names = [
"Dr. Heidi Karin Hirsch",
"Miss Arlene Auerbach",
"Mr. and Mrs. Larry Zoom",
"Mr. Frank Paul Lummer",
"Vicepresident Colter"
]

print "Original list of names:"
for name in names:
    print name

print
print "List of names sorted by last name:"
names_sorted = sort_names(names)
for name in names_sorted:
    print name

"""
output -->
Original list of names:
Dr. Heidi Karin Hirsch
Miss Arlene Auerbach
Mr. and Mrs. Larry Zoom
Mr. Frank Paul Lummer
Vicepresident Colter

List of names sorted by last name:
Miss Arlene Auerbach
Vicepresident Colter
Dr. Heidi Karin Hirsch
Mr. Frank Paul Lummer
Mr. and Mrs. Larry Zoom
"""
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.