The Fibonacci series of integers was orignally used in biology to predict the population increase of rodents, or the branching of the veins in a leaf (top to stem).

A Fibonacci number series is made by adding the current number to the previous number to get the next mumber. According to http://en.wikipedia.org/wiki/Fibonacci_number the series starts with 0, 1

This is one of the fastest ways to calculate the Fibonacci series:

``````def fibo3( n ):
(current, previous) = (0, 1)
k = n
while k > 0:
# use a tuple swap
(current, previous) = (previous, current + previous)
k -= 1
return current

for n in range(13):
print fibo3(n),

"""
example output:
0 1 1 2 3 5 8 13 21 34 55 89 144
"""``````

This is probably the sweetest way to create a list of the series:

``````fibo_list = [0,1]
for n in range(input('Enter an integer (>0): ')-1):
fibo_list.append(fibo_list[-2] + fibo_list[-1])
print fibo_list

"""
example output:
Enter an integer (>0): 12
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]
"""``````

Note: changed php code field tags, don't work properly any more.

So, you want to do a Google search from your Python program, here is the code:

``````# search Google

import webbrowser

search_str = raw_input("Enter Google search string: ")

# convert to a list and process
qlist = search_str.split(None)
list1 = []
for q in qlist:
if '+' in q:
q = q.replace('+', '%2B')
if ' ' in q:
q = '"%s"' % q
q = q.replace(' ', '+')
list1.append(q)

# convert back to a string
query = '+'.join(list1)

webbrowser.open(url)``````

Let's say you would like to print 105 numbers and like to show 10 numbers to a row. Here is an example how you can do this using tuple indexing ...

``````# creating a table of list items
# shows width list items separated by a tab in each row
# uses tuple indexing, selects tuple index False=0 or True=1
# depending on k % width == width-1 compare result

# items per row
width = 10
for k, item in enumerate(range(1, 106)):
# indexes width-1 tabs followed by one newline
tab_or_newline = ('\t', '\n')[k % width == width-1]
print "%3s%s" % (item, tab_or_newline),

print``````

To better familiarize you with Python's 'for loop', here are some experiments ...

``````# playing around with Python 'for loops'
# for large ranges replace range() with the more efficient xrange()

print "iterate over 0 to <6:"
for k in range(6):
print k
print '-'*30  # print 30 dashes

print "show odd numbers from 1 to 5:"
for k in range(1, 6, 2):
print k
print '-'*30

print "print a table of square roots:"
for x in range(1, 7):
print "the squareroot of %d is %0.4f" % (x, x**0.5)
print '-'*30

print "iterate over 0 to <10 and skip a few numbers:"
for k in range(10):
# skip values > 3 or < 7
if 3 < k < 7:
continue
print k
print '-'*30

print "start at 11, finish > 0 and decrement by 2:"
for x in range(11, 0, -2):
print x
print '-'*30

print "iterate over a tuple of choices:"
for cuisine in "spam", "eggs", "cumquats":
print "I do love", cuisine
print '-'*30

print "spell out a string:"
for c in "hello":
print c
print '-'*30

print "create a string of 'a' to 'z' characters:"
s = ""
for c in range(ord('a'), ord('z') + 1):
s += chr(c)
print s
print '-'*30

print "create a simple histogram:"
data = 1, 3, 6, 9, 7, 4, 2
for x in data:
print '*' * x
print '-'*30

def qrange(start, stop=None, step=1):
"""
similar to xrange() but handles floats
"""
# when only one arg is given ...
if stop == None:
stop = start
start = 0
# allow for decrement
if step < 0:
while start > stop:
# yield makes this a generator
yield start
start += step
else:
while start < stop:
yield start
start += step

print "testing list(qrange(0.2, 10, 1.5)):"
print list(qrange(0, 10, 1.5))
print '-'*30

print "the 'for loop' iterates over qrange(1, 2, 0.3):"
for x in qrange(1, 2, 0.3):
print x

"""
output -->
iterate over 0 to <6:
0
1
2
3
4
5
------------------------------
show odd numbers from 1 to 5:
1
3
5
------------------------------
print a table of square roots:
the squareroot of 1 is 1.0000
the squareroot of 2 is 1.4142
the squareroot of 3 is 1.7321
the squareroot of 4 is 2.0000
the squareroot of 5 is 2.2361
the squareroot of 6 is 2.4495
------------------------------
iterate over 0 to <10 and skip a few numbers:
0
1
2
3
7
8
9
------------------------------
start at 11, finish > 0 and decrement by 2:
11
9
7
5
3
1
------------------------------
iterate over a tuple of choices:
I do love spam
I do love eggs
I do love cumquats
------------------------------
spell out a string:
h
e
l
l
o
------------------------------
create a string of 'a' to 'z' characters:
abcdefghijklmnopqrstuvwxyz
------------------------------
create a simple histogram:
*
***
******
*********
*******
****
**
------------------------------
testing the list(qrange(0.2, 10, 1.5)):
[0, 1.5, 3.0, 4.5, 6.0, 7.5, 9.0]
------------------------------
the 'for loop' iterates over qrange(1, 2, 0.3):
1
1.3
1.6
1.9
"""``````

Grandma Vegaseat gets her Social Security Payment deposited on the third Wednesday of each month, so I wrote her this little Python program ...

``````# print out the third Wednesdays of each month in a given year

import calendar

# makes Monday first day of week (this is the default)
calendar.setfirstweekday(calendar.MONDAY)

year = int(raw_input("Enter year: "))
print "The third Wednesdays of each month in %d:" % year
for month in range(1, 13):
k = 0
for day in range(1, 32):
try:
weekday = calendar.weekday( year, month, day)
except ValueError:
continue
if weekday == calendar.WEDNESDAY:
k += 1
if k == 3:
# format the result
print "%02d/%02d/%d" % (month, day, year)

"""
Enter year: 2007
The third Wednesdays of each month in 2007:
01/17/2007
02/21/2007
03/21/2007
04/18/2007
05/16/2007
06/20/2007
07/18/2007
08/15/2007
09/19/2007
10/17/2007
11/21/2007
12/19/2007
"""``````

Just a couple of code samples to show you how you can get started with Graphics User Interface (GUI) programming. I am using the Tkinter GUI toolkit since it is simple to use and is included in most Python installations.

Here is the simple and rather blah console version ...

``````print "Hello, world!"

raw_input("Press Enter to go on ... ")  # console output wait``````

Tkinter to the rescue, to create at least a window ...

``````# a simple "Hello, world!" Tkinter GUI

# import Tkinter as namespace tk
import Tkinter as tk

# create the basic window, let's call it 'root'
root = tk.Tk()

# create a label
label1 = tk.Label(root, text="Hello, world!")
# pack the label into the window
label1.pack()

# run the GUI event loop
root.mainloop()``````

Still blah, let's add some color ...

``````# a simple "Hello, world!" Tkinter GUI

# import Tkinter as namespace tk
import Tkinter as tk

# create the basic window, let's call it 'root'
root = tk.Tk()

# create a label with colors in it
label1 = tk.Label(root, text="Hello, world!", fg='red', bg='yellow')
# pack the label into the window
label1.pack()

# run the GUI event loop
root.mainloop()``````

Looks a little better, but we should really make the text stand out ...

``````# a simple "Hello, world!" Tkinter GUI
# add some color and a larger text font

# import Tkinter as namespace tk
import Tkinter as tk

# create the basic window, let's call it 'root'
root = tk.Tk()

# create a label with colors in it
# note that the label auto-expands to fit the large text
font1 = ('times', 30, 'bold')
label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
# pack the label into the window
label1.pack()

# run the GUI event loop
root.mainloop()``````

Hey, looks flashy, can we change the colors? Maybe with a button click ...

``````# a simple "Hello, world!" Tkinter GUI
# add some color and a larger text font
# add buttons to change text color

# import Tkinter as namespace tk
import Tkinter as tk

def white_blue():
label1.config(fg='white', bg='blue')

def blue_green():
label1.config(fg='blue', bg='green')

# create the basic window, let's call it 'root'
root = tk.Tk()

# create a label with colors in it
font1 = ('times', 30, 'bold')
label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
# let's use a grid to put the label into the window
# make it span two grid columns
label1.grid(row=0, column=0, columnspan=2)
# create 2 buttons to click for text color change
# use the two grid positions below the label
# (by default the button will take up the center of each grid space)
button1 = tk.Button(root, text="white on blue", command=white_blue)
button1.grid(row=1, column=0)
button2 = tk.Button(root, text="blue on green", command=blue_green)
button2.grid(row=1, column=1)

# run the GUI event loop
root.mainloop()``````

Almost there, let's fancy up the buttons and give the window a befitting title ...

``````# a simple "Hello, world!" Tkinter GUI
# add some color and a larger text font
# add buttons to change text color and fancy them up

# import Tkinter as namespace tk
import Tkinter as tk

def white_blue():
label1.config(fg='white', bg='blue')

def blue_green():
label1.config(fg='blue', bg='green')

# create the basic window, let's call it 'root'
root = tk.Tk()
# why not add a title
root.title("Hello World from DaniWeb!")

# create a label with colors in it
font1 = ('times', 36, 'bold')
label1 = tk.Label(root, text="Hello, world!", font=font1, fg='red', bg='yellow')
# let's use a grid to put the label into the window
# make it span two grid columns
label1.grid(row=0, column=0, columnspan=2)
# create 2 buttons to click for text color change
# use the two grid positions below the label
# (by default the button will take up the center of each grid space)
# give the buttons some y-axis space and a ridge style
button1 = tk.Button(root, text="white on blue", relief='ridge', command=white_blue)
button2 = tk.Button(root, text="blue on green", relief='ridge', command=blue_green)

# run the GUI event loop
root.mainloop()``````

I hope the development of the GUI code made sense to you, and you are willing to convert one of your console programs to the colorful world of mouse clicks.

John Zelle has written a graphics module (a thin wrapper for Tkinter) that makes GUI coding fairly simple. This module is popular with a number of schools ...
http://mcsp.wartburg.edu/zelle/python/graphics.py
He also has provided nice documentation ...
http://mcsp.wartburg.edu/zelle/python/graphics/graphics.pdf

Every computer language has to have its bouncing ball code example. Here is the bouncing ball using Python's pygame module ...

``````# experiments with module pygame
# free from: [url]http://www.pygame.org/[/url]
# bounce a red ball

import pygame as pg

# initialize pygame
pg.init()

# use this image file or an image file you have
# pygame allows these image formats .bmp  .jpg  .png  .gif
image_file = "ball_r.gif"

# image moves [x, y] at a time
im_dir = [2, 1]

# pygame uses an RGB color tuple
black = (0,0,0)
# screen width and height
sw = 600
sh = 480
# create a screen
screen = pg.display.set_mode((sw, sh))
# give the screen a title
pg.display.set_caption('bouncing ball (press escape to exit)')

# load the ball image file
# get the rectangle the image occupies
im_rect = image.get_rect()

# the event loop also loops the animation code
while True:
pg.event.pump()
keyinput = pg.key.get_pressed()
# exit on corner 'x' click or escape key press
if keyinput[pg.K_ESCAPE] or pg.event.peek(pg.QUIT):
raise SystemExit

# set the move
im_rect = im_rect.move(im_dir)
# detect the boundaries and change directions
# left/right boundaries are 0 to sreen width
if im_rect.left < 0 or im_rect.right > sw:
im_dir[0] = -im_dir[0]
# top/bottom boundaries are 0 to screen height
if im_rect.top < 0 or im_rect.bottom > sh:
im_dir[1] = -im_dir[1]
# this erases the old sreen with black
screen.fill(black)
# put the image on the screen
screen.blit(image, im_rect)
# update screen
pg.display.flip()``````

The image file of a red ball is attached.

Note: Pygame hasn't been released for Python25 yet. They are asking fo a few more weeks to perfect Pygame181.

Just short example how to build very simple pygame program (similar to vegaseat's Hello):

``````# module pygame free from: http://www.pygame.org
# "Hello World" with colour and nice font

import pygame as pg

# initialize pygame
pg.init()

# RGB colour tuple pygame uses
yellow = (255,255,0)

# create screen/surface of width=480 and height=80
screen = pg.display.set_mode((380, 60))
pg.display.set_caption('Hello World from DaniWeb!')

# create surface (canvas) in memory
surface = pg.Surface(screen.get_size())
# fill surface
surface.fill(yellow)

# display some text in given font
font = pg.font.SysFont('Comic Sans MS', 36)
text = font.render("Hello World!", 1, (10, 10, 10))
textpos = text.get_rect()
# have text center coincide with surface center position
textpos.centerx = surface.get_rect().centerx
# transfer text area to surface area (now centered)
surface.blit(text, textpos)

# transfer surface area to screen area at ulc x=0,y=0
screen.blit(surface, (0, 0))
# update to show it on the computer display
pg.display.flip()

# run event loop and provide exit conditions
while True:
for event in pg.event.get():
# the title 'x' click
if event.type == pg.QUIT:
raise SystemExit``````

Here is an example of making a simple 'guess a number game' more appealing using the Tkinter GUI toolkit and multiple buttons ...

``````# Tkinter 'guess an integer' game

from Tkinter import *
import random
import time

class NumberGuess(object):
def __init__(self, root):
self.root = root
# let the user know what is going on
self.label1 = Label(root, text="Guess a number between 1 and 10", bg='yellow')
self.label1.place(x=10, y=10)
# prompt the user
self.label2 = Label(root, text="Click the button of your guess:")
self.label2.place(x=10, y=35)
# the result displays here
self.label3 = Label(root, text="", bg='green')
self.label3.place(x=10, y=100, width=200, height=20)
# create a row of ten buttons
self.make_buttons()
# pick a random integer from 1 to 10
self.rn = random.randrange(1, 11)

def make_buttons(self):
"""make ten buttons in a row labeled 1 to 10"""
self.buttons = [None]
x = 10
for index in range(1,11):
self.buttons.append(
Button(self.root, text=index, fg="black", width=1,
command=lambda i=index: self.click(i)))
self.buttons[-1].place(x=x, y=60)
x += 20

def reset_buttons(self):
for index in range(1,11):
self.buttons[index].configure(fg='black')

def click(self, index):
root.title('Guess!')
self.label3['bg'] ='green'
# this will mark the number picked in red
self.buttons[index].configure(fg='red')
num = int(index)
guess = " (%s)" % num
# check it out
if num > self.rn:
self.label3['text'] = 'Lower!' + guess
elif num < self.rn:
self.label3['text'] = 'Higher!' + guess
else:
self.label3['bg'] ='red'
self.label3['text'] = 'Guessed correctly!' + guess
root.title('New game!')
# reset all buttons to black
self.reset_buttons()
# new game, set new random number
self.rn = random.randrange(1, 11)

root = Tk()
root.title()
root.geometry("240x130+30+30")
app = NumberGuess(root)
root.mainloop()``````

I don't see much here on generators. They are a nice feature of Python that everyone should know.

Generators are neat ways of doing certain things that involve iterative work. For example, instead of calling a fibonacci function to return fibonacci numbers in a list (say), we create a generator object and iterate over it to return objects one at a time. That way we get them when we need them and can toss them when we're done. In its simplest form with no upper limit:

``````>>> def fiball():
...     x0 = 1
...     x1 = 1
...     yield x0
...     while True:
...             yield x1
...             xNext = x0+x1
...             x0=x1
...             x1=xNext
...
>>> fg = fiball()
>>> fg
<generator object at 0x00D87DA0>
>>> fg.next()
1
>>> fg.next()
1
>>> fg.next()
2
>>> fg.next()
3
>>> fg.next()
5
>>> for i in range(13):
...     print fg.next(),
...
8 13 21 34 55 89 144 233 377 610 987 1597 2584
>>>``````

Calling `fiball()` returns a generator object, rather than doing any calculations. Whenever you invoke the generator object's `next()` method, you cause the generator's code to execute until it hits a `yield X` , at which point it remembers its state and returns X. Further calls to `next()` continue the generator's execution after the `yield` statement, picking up right where it left off. So there's sort of a ping-pong effect, with `next()` invoking the generator where it left off, and `yield` returning the "next" value.

The generator code looks just like a function definition. The presence of a `yield` statement is what tells Python this is a generator instead of a function.

Sometimes you want to have a generator "stop generating", analagous to the way range(10) has a defined stopping point. The generator would do this by just returning. We can modify the above generator to accept an upper limit and return when we have exceeded that limit. The result looks like:

``````def fibmax(upper_limit):        # Parameter is new
x0 = 1
x1 = 1
yield x0
while x1 < upper_limit: # Not always true
yield x1
xNext = x0+x1
x0=x1
x1=xNext
# Fall thru to here when we pass upper_limit, exiting the generator

fm = fibmax(1000) # Generate fibonacci's up to 1000
for xx in fm:      # Iterate over the fm object
print xx,``````

Produces the output: `1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987` Of course, you're not limited to making sequential calls to the `next()` method, you can execute arbitrary code between successive `next()` calls. And you can create multiple generators from the same object, each with their own separate context.

The best features of generators require Python 2.5 or later. There's good documentation at the python website.

Thanks BearofNH, very nice contribution on generators. If you work with generators, you will find module itertools very handy. Here is an example ...

``````# use itertools.islice(iterable, [start,] stop [, step])
# to get selected results of a generator function ...

from itertools import islice

def fibo_generator():
"""
a generator for Fibonacci numbers, goes
to next number in series on each call
"""
current, previous = 0, 1
while True:
yield current
# use a tuple swap
current, previous = previous, current + previous

print "show Fibonacci number for n = 10:"
for k in islice(fibo_generator(), 10, 11):
print k,

print; print

print "show Fibonacci series for n = 7 to 10:"
for k in islice(fibo_generator(), 7, 11):
print k,``````
commented: great find +13

This shows you how you can use a background image in your Tkinter GUI programs. I used PIL to be able to load image formats other than the 'Tinter only .gif' ...

``````# use a Tkinter label as a panel for a background image
# note that Tkinter only reads .gif and .ppm images
# use the Python Image Library (PIL) for other image formats
# free from [url]http://www.pythonware.com/products/pil/index.htm[/url]
# give Tkinter a namespace to avoid conflicts with PIL
# (they both have a class named Image)

import Tkinter as tk
from PIL import Image, ImageTk

root = tk.Tk()
root.title('background image')

# pick an image file you have .bmp  .jpg  .gif.  .png
# load the file and covert it to a Tkinter image object
imageFile = "Flowers.jpg"
image1 = ImageTk.PhotoImage(Image.open(imageFile))

# get the image size
w = image1.width()
h = image1.height()

# position coordinates of root 'upper left corner'
x = 0
y = 0

# make the root window the size of the image
root.geometry("%dx%d+%d+%d" % (w, h, x, y))

# root has no image argument, so use a label as a panel
panel1 = tk.Label(root, image=image1)
panel1.pack(side='top', fill='both', expand='yes')

# put a button on the image panel to test it
button2 = tk.Button(panel1, text='button2')
button2.pack(side='top')

# save the panel's image from 'garbage collection'
panel1.image = image1

# start the event loop
root.mainloop()``````

To copy and paste this code into your editor without the line numbers, click on the 'Toggle Plain Text' area. Now you can highlight and copy.

Thanks for the itertools tip, vegaseat. And the much tighter generator code.
Almost makes you wonder if Python could be enhanced to allow subscript/slice syntax to "index" generators, as in:

``````>>>g = fibo_generator()
>>>print g[0:10]
0 1 1 2 3 5 8 13 21 34 55``````

Of course there would be a number of semantic issues to work out, such as stability of results.

If you want to determine the size of a file folder and it's subfolders, use this handy little utility ...

``````# determine size of a given folder in MBytes

import os

# pick a folder you have ...
folder = 'D:\\zz1'
folder_size = 0
for (path, dirs, files) in os.walk(folder):
for file in files:
filename = os.path.join(path, file)
folder_size += os.path.getsize(filename)

print "Folder = %0.1f MB" % (folder_size/(1024*1024.0))``````

For those of you, who absolutely have to clear the console screen, you can use:

``print '\n'*35``

This of course leaves the cursor at the bottom of the screen. If you don't like that, this will do better:

``````# works on Windows or Linux, also Vista
import os
os.system(['clear','cls'][os.name == 'nt'])``````

For those of you who like visual frame builders/designers for the wxPython toolkit, wxGlade has been much improved lately. You can down load it free from:

It also comes integrated into Stani's Python Editior (SPE), which is still available from:
Downloads as spe-0.8.3c.zip, and will work with Python 2.3 - 2.5. Simply extract the '_spe' directory into your Python 'lib' folder. You can then run 'spe.pyw' from there. Again, you need the wxPython GUI toolkit installed first for SPE and wxGlade to work!

wxGlade takes one moment to get used to, there is one short tutorial.

An example how to set up a wxPython GUI toolkit application with Boa Constructor, an IDE with a built in visual frame builder/designer along the line of the Delphi RAD tool.

These are the instructions how work with a wx.ListBox:

Then run Boa.exe

(this will allow you to create just one source file).

2) Click on the 'frame designer' button (square box with up arrow),
the frame shows and you can drag it more to the center of the screen,
away from the Inspector information.
You can drag the edges of the frame to change the size.
Size and position details show in the 'Constr' page of the Inspector.

3) Open the Inspector 'Props' page, move to BackGroundColour and
click on (wx.Colour) then on the '...' button.
Pick a background color from the colour palette (eg. green),
the frame will fill with the selected colour.

4) Click on the 'Buttons' tab and select a wx.Button.
Drop it on the frame somewhere near the top.
Drop two more wx.buttons near the frame bottom.
We will drag them to the correct position later.

5) Click on the 'List Controls' tab and select a wx.ListBox.
Drop it on the middle of the frame.
You can stretch the ListBox to the size you want, and
drag it to right position on the frame.

6) Now position the buttons where you want them.
Drag button1 to top of the list, button2 and button3
just below the list.

7) Let's label the buttons ...
click on button1 and in the Inspector 'Constr' page look
for Label and type in 'Load List'.
Similarly label button2 'Sort List' and button3 'Clear List'.

8) Leave the Inspector by clicking on the v shaped checkmark icon
(Post the session).
You can now take a look at the the source code Boa has created
so far. To make this an executable module, put the cursor at
the end of the code, and click an 'Edit'/'Add Module Runner'. This
will add the necessary code to the end of the file. It will run the code
as a wx.PySimpleApp().

9) It's time we save our efforts via File/Save or clicking
the filesave icon. You may want to create a new folder and
save the program as 'wxListBoxTest1.py'

10) After you have saved the program code, you can test drive it
by clicking on the blue triangle icon (Run module). Admire
it and then exit your program you have just created.

11) Now we have to bind the buttons to a button click event.
Go back to the Frame Designer (up arrow in a square block icon).
Select the 'Load List" button by clicking on it. In the Inspector's
'Evts' page double click on 'ButtonEvent' and then double click on the
resulting 'wx.EVT_BUTTON'. There will be an entry below that
telling you that the button click is bound to a function called
'OnButton1Button'.

12) Leave the Inspector by clicking on the v shaped checkmark icon,
and look a the changed source code, there will be a
button1.Bind() statement and the function definition named
'OnButton1Button()'.

13) Return to the Frame Designer and do the same operations for
button2 (Sort) and button3 (Clear).
Click on the ListBox and move to the Inspector's 'Evts' page.
Double click on 'ListBoxEvent' and then on 'wx.EVT_LISTBOX'.
This will bind to a function called 'OnListBox1Listbox'.

14) Your Windows frame is now designed, so leave the Inspector
(v shaped checkmark icon). Look over the generated code.
The various generated function have a place holder statement
'event.Skip()'. You need to replace this statement with the

Add strings to the ListBox with:
self.listBox1.Append("some string")
Get the selected string from the LisBox with:
selected = self.listBox1.GetStringSelection()

Clear the ListBox strings with
self.listBox1.Clear()

Sorting is done by transferring the ListBox strings to
regular Python list container with:
name_list = self.listBox1.GetItems()
Then sort the list and reload the cleared ListBox with:
self.listBox1.Set(name_list)

15) Save any code modifications before you run the program!

Here is the resulting code ...

``````#Boa:Frame:Frame1

import wx

def create(parent):
return Frame1(parent)

[wxID_FRAME1, wxID_FRAME1BUTTON1, wxID_FRAME1BUTTON2, wxID_FRAME1BUTTON3,
wxID_FRAME1LISTBOX1,
] = [wx.NewId() for _init_ctrls in range(5)]

class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(355, 138), size=wx.Size(255, 385),
style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
self.SetClientSize(wx.Size(247, 345))
self.SetBackgroundColour(wx.Colour(0, 128, 0))

name='button1', parent=self, pos=wx.Point(16, 16),
size=wx.Size(87, 28), style=0)
self.button1.Bind(wx.EVT_BUTTON, self.OnButton1Button,
id=wxID_FRAME1BUTTON1)

self.button2 = wx.Button(id=wxID_FRAME1BUTTON2, label='Sort List',
name='button2', parent=self, pos=wx.Point(16, 296),
size=wx.Size(87, 28), style=0)
self.button2.Bind(wx.EVT_BUTTON, self.OnButton2Button,
id=wxID_FRAME1BUTTON2)

self.button3 = wx.Button(id=wxID_FRAME1BUTTON3, label='Clear List',
name='button3', parent=self, pos=wx.Point(136, 296),
size=wx.Size(87, 28), style=0)
self.button3.Bind(wx.EVT_BUTTON, self.OnButton3Button,
id=wxID_FRAME1BUTTON3)

self.listBox1 = wx.ListBox(choices=[], id=wxID_FRAME1LISTBOX1,
name='listBox1', parent=self, pos=wx.Point(16, 64),
size=wx.Size(208, 216), style=0)
self.listBox1.Bind(wx.EVT_LISTBOX, self.OnListBox1Listbox,
id=wxID_FRAME1LISTBOX1)

def __init__(self, parent):
self._init_ctrls(parent)

def OnButton1Button(self, event):
'''
click button to load the ListBox with names
'''
self.listBox1.Append("Andreas")
self.listBox1.Append("Erich")
self.listBox1.Append("Udo")
self.listBox1.Append("Jens")
self.listBox1.Append("Bjorn")
self.listBox1.Append("Heidrun")
self.listBox1.Append("Ulla")
self.listBox1.Append("Volger")
self.listBox1.Append("Helmut")
self.listBox1.Append("Freja")
self.listBox1.Append("Nathan")
self.listBox1.Append("Jerry")
self.listBox1.Append("Lamar")
self.SetTitle("Select a name ...")
#event.Skip()

def OnButton2Button(self, event):
'''
put the ListBox items into a Python list, sort and reload
'''
# GetItems() new in wxPython2.8
name_list = self.listBox1.GetItems()
name_list.sort()
self.listBox1.Set(name_list)
#event.Skip()

def OnButton3Button(self, event):
'''
click button to clear the ListBox items
'''
self.listBox1.Clear()
#event.Skip()

def OnListBox1Listbox(self, event):
'''
click ListBox item and display the selected string in the frame title
'''
selName = self.listBox1.GetStringSelection()
self.SetTitle(selName)
#event.Skip()

if __name__ == '__main__':
app = wx.PySimpleApp()
frame = create(None)
frame.Show()
app.MainLoop()``````

This doesn't matter too much, but in the code examples you wrote "Monte Python". I'm pretty sure it's spelt "Monty Python".

Editor's note: Thanks a lot! In this case it does matter, so I corrected this late night mistake!

If you are interested in 3D graphics, then you can use the free visual module from Visual Python (VPython) at: http://vpython.org/

Here is a nice example of a bouncing ball between two walls. Best of all, you can press the right mouse button to drag/rotate the view in space. An interesting module for any science oriented person ...

``````# bouncing a ball of the walls using VPython
# press the right mouse button to drag/rotate the whole thing
# experiments with visual Python from vpython.org

import visual as vs

# create a red ball
# create 2 green opposing walls
wall_right = vs.box(pos=(6, 0, 0), size=(0.2, 4, 4), color=vs.color.green)
wall_left = vs.box(pos=(-6, 0, 0), size=(0.2, 4, 4), color=vs.color.green)

# size movement of the ball
dt = 0.05
ball.velocity = vs.vector(2,0,0)

# loop it to create the animation
while True:
# time the moving ball, higher value gives faster speed
vs.rate(50)
ball.pos = ball.pos + ball.velocity * dt
# the ball needs to bounce as it touches the wall
if ball.x > wall_right.x - ball_radius:
ball.velocity.x = -ball.velocity.x
if ball.x < wall_left.x + ball_radius:
ball.velocity.x = -ball.velocity.x``````

If you work with Python dictionary objects, you can make them persistent to file using the module shelve ...

``````# ShelveData1.py
# create and initialize a class/structure and save the data to
# a shelve byte stream file that behaves like a dictionary

import shelve

# a Python class to mimic a C structure or Pascal record
class Person(object):
"""__init__() functions as the class constructor"""
def __init__(self, name=None, sex=None, slogan=None):
self.name = name
self.sex = sex
self.slogan = slogan

def __getattr__(self, attr):
if attr == 'firstname':
# assumes name = "first last", slice to the first space
return self.name[0:self.name.find(" ")]
else:
raise AttributeError

# initialize and load the class (structure) like this ...
emma = Person("Emma Porke", "female", "Vote for Bush and Dick")
jack = Person("Jack Schidd", "male", "Never give a schidd!")

# ... or like this (looks more like C) ...
arnie = Person()
arnie.name = "Arnold Negerschwarz"
arnie.sex  = "often"
arnie.slogan = "I know how to spell nukilar!"

# this will open or create a shelve file called 'Slogan.SLV'
dbs1 = shelve.open('Slogan.SLV')

# note that a shelve file behaves like a {obj.name:object} dictionary
for obj in (arnie, emma, jack):
# creating the dictionary will automatically save the data to file
# for each pair key is the objects name and the value is the object
dbs1[obj.name] = obj

# let's add one more ...
frank = Person("Frank Palermo", "male", "An innuendo is a suppository")
# again, this will automatically save the data to file
dbs1[frank.name] = frank

print "Saved all data to shelve file 'Slogan.SLV'"

# done adding any additional data, close the file (optional, but a good habit)
dbs1.close()``````

Now the dictionary you worked with has been made persistent in file 'Slogan.SLV' and you can open this file and work with the dictionary ...

``````# ShelveData2.py
# load the shelve file 'Slogan.SLV' that was created in ShelveData1.py

import shelve

# you need the same class you used for writing the shelve data, but
class Person(object):
"""__init__() functions as the class constructor"""
def __init__(self, name=None, sex=None, slogan=None):
self.name = name
self.sex = sex
self.slogan = slogan

def __getattr__(self, attr):
if attr == 'firstname':
# assumes name = "first last", slice to the first space
return self.name[0:self.name.find(" ")]
elif attr == 'lastname':
# assumes name = "first last", slice from the first space
return self.name[self.name.find(" ")+1:]
elif attr == 'title':
# automagically creates a title for the person
if self.sex == 'male':
return "Mister"
elif self.sex == 'female':
return "Miss"
else:
return "Rep."
else:
raise AttributeError

# open the previously created shelve data file
dbs2 = shelve.open('Slogan.SLV')

# test it, remember that shelve data work like a dictionary
# these are the keys (the objects names)
print dbs2.keys()            # ['Jack Schidd', 'Arnold Negerschwarz', 'Emma Porke']

# to access data you can use
print "Emma's slogan:", dbs2['Emma Porke'].slogan

# or simply reestablish objects emma, jack, arnie and frank
emma = dbs2['Emma Porke']
jack = dbs2['Jack Schidd']
arnie = dbs2['Arnold Negerschwarz']
frank = dbs2['Frank Palermo']

print

print "Just objects emma and jack:"
print '%s says "%s"' % (emma.name, emma.slogan)
print '%s says "%s"' % (jack.name, jack.slogan)

print

# show it the Pythonian way (good for large person lists) ...
print "The whole list of names (the Pythonian way):"
personList = [emma, jack, arnie, frank]
for pers in personList:
#print '%s says "%s"' % (getattr(pers, "name"), getattr(pers, "slogan"))
# simpler ...
print '%s says "%s"' % (pers.name, pers.slogan)

print

# this works without establishing objects like emma, jack and arnie ...
# the order will be the dictionary's key order
print "The whole list (the generic way):"
for key in dbs2.keys():
exec("x = dbs2[key]")
print '%s %s says "%s"' % (x.title, x.lastname, x.slogan)

print

# or you can search selected data ...
print "A search of selected data:"
for key in dbs2.keys():
exec("x = dbs2[key]")
if x.firstname == "Arnold":
print '%s says "%s"' % (x.firstname, x.slogan)
if x.lastname == "Porke":
print '%s %s says "%s"' % (x.title, x.name, x.slogan)

# any changes you make to the dictionary will be
# automatically saved to file, let's try this
jack.slogan = "No more schidd!"

print

# test it ...
print "Modified data:"
personList = [emma, jack, arnie, frank]
for pers in personList:
print '%s says "%s"' % (pers.firstname, pers.slogan)``````
commented: neat +13

An example for how to search a dictionary with key: value pairs for both the value and the key:

``````# search a dictionary for key or value

def find_key(dic, val):
"""return the key of dictionary dic given the value"""
return [k for k, v in symbol_dic.iteritems() if v == val][0]

def find_value(dic, key):
"""return the value of dictionary dic given the key"""
return dic[key]

# test it out
if __name__ == '__main__':
# dictionary of chemical symbols
symbol_dic = {
'C': 'carbon',
'H': 'hydrogen',
'N': 'nitrogen',
'Li': 'lithium',
'Be': 'beryllium',
'B': 'boron'
}

print find_key(symbol_dic, 'boron')  # B
print find_value(symbol_dic, 'B')    # boron``````

Sometimes you just have to clear the display screen when you work with the Python command shell. This little function does that in both Windows or Linux:

``````def clear_screen():
"""
clear the screen in the command shell
works on windows (nt, xp, Vista) or linux
"""
import os
os.system(['clear','cls'][os.name == 'nt'])

# test module out
if __name__ == '__main__':
import time
print "some text on the screen for a few seconds"
# wait 2.5 seconds
time.sleep(2.5)
# now clear the screen
clear_screen()
# wait
time.sleep(1.5)
print "test completed"
raw_input("press enter to go on ")``````

You can save the whole module as clear_screen.py and import it into your program.

Just an updated way to count the frequency of letters in a text ...

``````# count the character frequency in a text:
# create a list of unique (frequency, character) tuples
# then sort and display highest frequency characters first

text = 'mississippi mudslide'

# create a list of characters from the text
c_list = list(text)

# make a list of (frequency, char) tuples, use set() to avoid duplicates
fc_list = [(c_list.count(c), c) for c in set(c_list) if c.isalpha()]

for item in sorted(fc_list, reverse=True):
print "%s --> %s" % (item[1], item[0])

"""
my output -->
s --> 5
i --> 5
p --> 2
m --> 2
d --> 2
u --> 1
l --> 1
e --> 1
"""``````

You can rewrite the code to count words in a text.
The following code may not be simpler, but it is slightly faster then the set code ...

``````# count the character frequency in a text
# a slightly faster option using a dictionary instead of a set ...
from operator import itemgetter

text = 'mississippi mudslide'
d = {}
for c in text:
if c.isalpha():
d[c] = d.get(c, 0) + 1

for k, v in sorted(d.items(), key=itemgetter(1), reverse=True):
print "%s --> %s" % (k, v)

"""
my output -->
i --> 5
s --> 5
d --> 2
m --> 2
p --> 2
e --> 1
l --> 1
u --> 1
"""``````

You have two lists, one list with all the cities you wanted to visit in your life, and another list of cities you have already visited. Now you want to create a new list of cities you have not visited yet:

``````# subtract/remove elements of one list from another

city = ['Lisbon', 'Paris', 'Reno', 'London', 'Oslo', 'Ypsilanti']

visited = ['Reno', 'Ypsilanti']

not_visited = [c for c in city if c not in visited]
# order of remaining elements has not changed
print not_visited

# simpler ...
not_visited = list(set(city) - set(visited))
# order of remaining elements has changed
print not_visited

"""
my result --->
['Lisbon', 'Paris', 'London', 'Oslo']
['Paris', 'Oslo', 'London', 'Lisbon']
"""``````

One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.

``````# a function to return the numeric content of a cost item
# for instance \$12.99 or -\$123456789.01 (deficit spenders)
def getVal(txt):
if txt[0] == "\$":    # remove leading dollar sign
txt = txt[1:]
if txt[1] == "\$":    # could be -\$xxx
txt = txt[0] + txt[2:]

while txt:           # select float or integer return
try:
f = float(txt)
i = int(f)
if f == i:
return i
return f
except TypeError:  # removes possible trailing stuff
txt = txt[:-1]
return 0

# test the function ...
print getVal('-\$123.45')``````

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

So, I was trying to go through this code and understand. But I have a few questions on it. And please bear with me I'm just starting to learn python.

``txt = txt[0] + txt[2:]``

Why did you add the two together?

I'm also confused on that while loop. Why do you retrun i, f, and 0. And what exactly is it doing line by line.

Any help would be much appreciated.

Thanks

http://www.daniweb.com/forums/post104844-2.html

You can use the local variable dictionary vars() to create new variables on the fly:

``````food = 'bread'
vars()[food] = 123

Print vars() after line 1 and 2 to follow what's happening.

A function to allow for a relatively secure input of dates:

``````# a more secure way to enter a date

import datetime as dt

def enter_date():
"""
asks to enter year, month and day and returns
date info as <type 'datetime.datetime'>
"""
def extract_date(s):
try:
# month given as a decimal number
date = dt.datetime.strptime(s, "%d %m %Y")
except:
try:
# month given as a 3 letter abreviation
date = dt.datetime.strptime(s, "%d %b %Y")
except:
return None
return date

while True:
year = raw_input("Enter year (eg. 1979): ")
# you can enter number of month, full name or 3 letter abbreviation
month = raw_input("Enter month (eg. 9 or sep): ")
day = raw_input("Enter the day of the month: ")
date = extract_date(day + " " + month[:3].title() + " " + year)
if date == None:
print "Illegal info!"
continue
else:
return date

date = enter_date()

# testing ...
#print date, type(date)           # 2001-09-11 00:00:00 <type 'datetime.datetime'>
#print date.strftime("%m/%d/%Y")  # 09/11/2001
#print date.strftime("%d%b%Y")    # 11Sep2001

# do something with it ...
today = dt.datetime.today()
age = today - date
# assumes week starts with Monday
weekdays = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
week_day = weekdays[dt.date.weekday(date)]
print "Today is %s" % today.strftime("%d%b%Y")
print "%s was %d days ago on a %s" % (date.strftime("%d%b%Y"), age.days, week_day)

"""
my output -->
Enter year (eg. 1979): 2001
Enter month (eg. 9 or sep): september
Enter the day of the month: 11
Today is 03Mar2008
11Sep2001 was 2365 days ago on a Tuesday
"""``````

Thanks to Jeff for the idea.

Sorry!

Here is an example how to output a formatted table from a loop:

``````# print a table (16 columns) of ASCII characters from 1 to 127

# Bumsfeld, thanks for the dictionary
controls_dic = {
1: 'SOH', 2: 'STX', 3: 'ETX', 4: 'EOT', 5: 'ENQ', 6: 'ACK', 7: 'BEL',
8: 'BS', 9: 'HT', 10: 'LF', 11: 'VT', 12: 'FF', 13: 'CR', 14: 'SO',
15: 'SI', 16: 'DLE', 17: 'DC1', 18: 'DC2', 19: 'DC3', 20: 'DC4', 21: 'NAK',
22: 'SYN', 23: 'ETB', 24: 'CAN', 25: 'EM', 26: 'SUB', 27: 'ESC', 28: 'FS',
29: 'GS', 30: 'RS', 31: 'US'}

n = 1
for k in range(1, 128):
if k < 32:
s = controls_dic[k]
else:
s = chr(k)
if n % 16 > 0:
print "%4s" % s,
else:
print "%4s" % s
n += 1``````

This modified Tkinter GUI code allows you to follow your character key strokes on the console display:

``````# KeyLogger.py
# show a character key when pressed without using Enter key
# hide the Tkinter GUI window, only console shows

import Tkinter as tk

def key(event):
if event.keysym == 'Escape':
root.destroy()
print event.char

root = tk.Tk()
print "Press a key (Escape key to exit):"
root.bind_all('<Key>', key)
# don't show the tk window
root.withdraw()
root.mainloop()``````
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.