Let's say you want to extract the text between two given words. Here is one way, at first we look at it step by step, and then we combine all the steps to one line of code:

# find the text between two given words

str1 = "the quick brown fox jumps over the lazy dog."
word1 = "the"
word2 = "fox"

# do it one step at a time ...

# first split
part1 = str1.split(word1, 1)

print part1         # ['', ' quick brown fox jumps over the lazy dog.']
print part1[-1]     # ' quick brown fox jumps over the lazy dog.'

# second split
part2 = part1[-1].split(word2, 1)

print part2         # [' quick brown ', ' jumps over the lazy dog.']
print part2[0]      # ' quick brown '

print '-'*40

# combine it all ...

print str1.split(word1, 1)[-1].split(word2, 1)[0]  # ' quick brown '
vegaseat commented: very nice code +10

The Tkinter GUI toolkit, that normally comes with the Python installation, contains a turtle module that allows you to draw items with a turtle along the lines of the old logo language.

First draw a simple line ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw a turtle line in a given direction and length

import turtle
import time

tp = turtle.Pen()
# optional pen color
# use (r, g, b) tuple
# colors r, g, b have values of 0.0 to 1.0
# default is black (0, 0, 0), (0, 0, 1.0) is blue
tp.color(0, 0, 1.0)

# from the center go to the right for 150 pixels
tp.right(0)
tp.forward(150)

# show the result for 3 seconds
time.sleep(3)

Something more elaborate, using a loop to draw a square ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw 4 turtle lines to form a square

import turtle
import time

tp = turtle.Pen()

# optional pen color
tp.color('red')

# form a square by drawing 4 lines of 100 pixels length
# changing the direction by 90 degrees (360/4) each time
for k in range(4):
    tp.right(90)
    tp.forward(100)

# show the result for 3 seconds
time.sleep(3)

Looky here, a simple pentagon adopting the square drawing approach ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw 5 turtle lines to form a pentagon

import turtle
import time

tp = turtle.Pen()

# optional pen color
tp.color('magenta')

# form a pentagon by drawing 5 lines of 100 pixels length
# changing the direction by 72 degrees (360/5) each time
for k in range(5):
    tp.right(72)
    tp.forward(100)

# show the result for 3 seconds
time.sleep(3)

Well, I leave it up to you to form a hexagon, octagon, or triangle.

Now to something more complex, a polygon connecting (x, y) coordinate tuples in a list ...

# module turtle is part of Tkinter
# draw turtle lines to given (x,y) coordinate points to form a polygon

import turtle
import time

tp = turtle.Pen()

# list of (x, y) coordinate tuples
# first and last tuples match to close the polygon
coordinates = [
(-100, 100),
(-50, 180),
(50, 10),
(100, -80),
(50, -40),
(-50, -60),
(-100, 100),
]

# by default the turtle starts in the center of canvas (0, 0)
# -x is to the left of center
# -y is down from center
# to start, move the pen to the first (x, y)
# coordinate point tuple with the pen up (no drawing)
tp.up()
tp.goto(coordinates[0])

# now loop through the coordinate points with the pen down to draw
tp.down()
for x, y in coordinates:
    tp.goto(x, y)

# show the result for 5 seconds
time.sleep(5)

The turtle moves around slow enough so you can follow the progress ...

# module turtle is part of Tkinter
# turtle starts in the center of canvas (0, 0) by default
# draw turtle circles with a given radius

import turtle
import time

tp = turtle.Pen()

tp.color('blue')
# above center
radius = 100
tp.circle(radius)
# one more circle to be cute
tp.circle(radius - 20)

tp.color('red')
# below center
radius = -100
tp.circle(radius)
# what the heck, one more circle
tp.circle(radius + 20)

# show the result for 3 seconds
time.sleep(3)

Wow turtle is fun to play with :)

import turtle, time

tp = turtle.Pen()
tp.color('blue')

for k in xrange(51):
    for j in xrange(k):
        tp.right(360/float(k))
        tp.forward(25)

time.sleep(3)

*Oops I didn't mean to post this here, it was supposed to be in the thread asking about turtle *sorry*

Editor's note: It's okay, we leave it here as an examle of good thinking.

The stable version of Python30 has been released, there are a number of critical changes to the syntax. Here is a look at the new print() that replaces the print statement ...

# in Python30 the print statement has been replaced with
# the Python30 print() function
# print([object, ...][, sep=' '][, end='n'][, file=sys.stdout]) 
# formatting can be done with string.format()

import math

print(123)  # 123 followed by newline, end='\n' is default
print()     # newline
print('hello', end=' ') # ends with a space rather then a newline
print('world')          # hello world
print()

# string is default and does not have a type specifier
# {0} and {1} index the format args
sf = 'the {0} jumped over the {1}!'
print(sf.format('mouse', 'moon'))

# allow 10 char spaces, left align (<) is default
print('the {0:10} jumped over the {1:10}!'.format('mouse', 'moon'))
# use right align (>)
print('the {0:>10} jumped over the {1:>10}!'.format('mouse', 'moon'))

"""
result =
the mouse jumped over the moon!
the mouse      jumped over the moon      !
the      mouse jumped over the       moon!
"""

print('-'*42)  # prints 42 dashes

# float formatting with type specifier f
print('x = {0:5.3f}'.format(1234.567))     # x = 1234.567
print('x = {0:12.9f}'.format(1234.567))    # x = 1234.567000000
print('x = {0:-12.9f}'.format(1234.567))   # x = 1234.567000000
print('x = {0:+12.9f}'.format(1234.567))   # x = +1234.567000000
print('x = {0:+12.9f}'.format(-1234.567))  # x = -1234.567000000
print('x = {0:012.3f}'.format(1234.567))   # x = 00001234.567
print()
print('x = {0:1.5e}'.format(1234.567))     # x = 1.23457e+03
print('x = {0:1.5e}'.format(0.000001234))  # x = 1.23400e-06
print('x = {0:1.5g}'.format(0.000001234))  # x = 1.234e-06
print()
print('x = {0:2.3%}'.format(0.337))        # x = 33.700%
print()
print('pi = {0:.3f}'.format(math.pi))   # pi = 3.142
print('pi = {0:.8f}'.format(math.pi))   # pi = 3.14159265
# the old C type % formatting will work (at least for a while)
print('pi = %.8f' % math.pi)            # pi = 3.14159265
print()
# integer formatting with type specifiers d, b, o, x
print('value = {0:2d}'.format(12))   # value = 12
print('value = {0:2b}'.format(12))   # value = 1100
print('value = {0:#2b}'.format(12))  # value = 0b1100
print('value = {0:2o}'.format(12))   # value = 14
print('value = {0:#2o}'.format(12))  # value = 0o14
print('value = {0:2x}'.format(12))   # value =  c
print('value = {0:#2x}'.format(12))  # value = 0xc

# also ...
print('value = {0:5}'.format(bin(12)))  # value = 0b1100
print('value = {0:5}'.format(oct(12)))  # value = 0o14
print('value = {0:5}'.format(hex(12)))  # value = 0xc

print('-'*40)

# using string functions
for x in range(1, 11):
    print(repr(x).rjust(2), repr(x*x).rjust(3), end=' ')
    # note use of end=' ' on previous line
    # puts in a space rather than a newline (default)
    print(repr(x*x*x).rjust(4))

print('-'*40)

# printing a table using format()
for x in range(1, 11):
    #
    print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))

print('-'*40)

"""
result =
 1   1    1
 2   4    8
 3   9   27
 4  16   64
 5  25  125
 6  36  216
 7  49  343
 8  64  512
 9  81  729
10 100 1000
"""

print('{0} and {1}'.format('spam', 'eggs'))  # spam and eggs
print('{1} and {0}'.format('spam', 'eggs'))  # eggs and spam

print('-'*40)

d = {
'milk' : 3.67,
'butter' : 1.95,
'bread' : 1.67,
'cheese' : 4.67
}
# print as a table
for food, price in d.items():
    print('{0:10} costs ${1:4.2f}'.format(food, price))
    
print('-'*40)

# use the dictionary directly
sf = 'Milk cost ${milk:4.2f}'
print(sf.format(**d))  # Milk cost $3.67

print('-'*40)

print("Printing out to a file ...")
fout = open("test123.txt", "a")
for food, price in d.items():
    print('{0:10} costs ${1:4.2f}'.format(food, price), file=fout)

The 'with' statement is now a Python key word ...

# in Python30 'with' is a key word

filename = "CanadaSong.txt"

data = """\
First come the black flies,
Then the Horse flies,
Then the Deer flies,
Then the snow flies!
"""

# here 'with' works like 'if True'
# the file handle is closed after the with block
with open(filename, "w") as fout:
    fout.write(data)

# 'with' works like 'if True'
# the file handle is closed after the with block
with open(filename) as fin:
    print(fin.readlines())

# testing file close ...
#print(fin.read())  # ValueError: I/O operation on closed file

I wouldn't rush using this new version of Python, since none of the popular third party modules like PyGame, wxPython, VPython and pywin32 have come out yet.

Decorator functions can simplify Python coding, here is an example:

# exploring decorator functions (new since Python24)
# which are higher functions that create new functions
#
# decorator functions are constructed using a function
# within a function (sometimes called wrapper functions)
# when you define a function inside of another function,
# any undefined local variables in the inner function will
# take the value of that variable in the outer function
# snee

def check_num(func):
    """
    a decorator function to check if another 
    function's argument is a number
    """
    def inner(arg):
        # arg is the argument of function func"""
        if type(arg) in (int, float):
            return func(arg)
        else:
            print("need numeric value as argument")
    return inner


# you apply the decorator with prefix @
# directly above the function you want to check
# this is equivalent to print_num = check_num(print_num)
@check_num
def print_num(n):
    print("Number = %s" % n)


# test ...
print_num(7)    # Number = 7
print_num(7.11) # Number = 7.11
print_num('a')  # need numeric value as argument

print('-'*40)

# check alternative approach ...
def print_num2(n):
    print("Number = %s" % n)

print_num2 = check_num(print_num2)

# test ...
print_num2(7)    # Number = 7
print_num2(7.11) # Number = 7.11
print_num2('a')  # need numeric value as argument

I am using the print() function, so it will work with Python25 and Python30.

One way to play music files of the popular MP3 music format, is to use the module pygame. Here is an example that works with a number of music file formats (you got to experiment):

# play a MP3 music file using module pygame
# (does not create a GUI frame in this case)
# pygame is free from: http://www.pygame.org/
# ene

import pygame

def play_music(music_file):
    """
    stream music with mixer.music module in blocking manner
    this will stream the sound from disk while playing
    """
    clock = pygame.time.Clock()
    try:
        pygame.mixer.music.load(music_file)
        print "Music file %s loaded!" % music_file
    except pygame.error:
        print "File %s not found! (%s)" % (music_file, pygame.get_error())
        return
    pygame.mixer.music.play()
    while pygame.mixer.music.get_busy():
        # check if playback has finished
        clock.tick(30)


# pick MP3 music file you have ...
# (if not in working folder, use full path)
music_file = "Drumtrack.mp3"

# set up the mixer
freq = 44100     # audio CD quality
bitsize = -16    # unsigned 16 bit
channels = 2     # 1 is mono, 2 is stereo
buffer = 2048    # number of samples (experiment to get right sound)
pygame.mixer.init(freq, bitsize, channels, buffer)

# optional volume 0 to 1.0
pygame.mixer.music.set_volume(0.8)

try:
    play_music(music_file)
except KeyboardInterrupt:
    # if user hits Ctrl/C then exit
    # (works only in console mode)
    pygame.mixer.music.fadeout(1000)
    pygame.mixer.music.stop()
    raise SystemExit

This is an example of how to use the with statement in python 3.0:

with open('test.txt') as f:
    print(f.readlines())

	
# output >> ['test']

For a python tutorial that is good for Python 3.0 Ene Uran pointed us to this link:

http://www.swaroopch.com/notes/Python_en:Table_of_Contents

It has an up to date tutorial brought to you from the people who made dive into python. So if your confused by lots of the posts here because python does not seem to be working have a look at that link, cause you most likely are dealing with python 3.0.

This simple code shows you the version of Python that is active on your computer:

# show the version of Python installed

import sys

print sys.version
print sys.version[ :3]

Just a simple pygame application to show you the basics:

# a simple pygame example
# creates a white circle on a black background
# the event loop makes exit from the program easier

import pygame

pygame.init()

# create a 300 x 300 display window
# the default background is black
win = pygame.display.set_mode((300, 300))

white = (255, 255, 255)
center = (100, 100)
radius = 20
pygame.draw.circle(win, white, center, radius)

# this puts the circle on the display window
pygame.display.flip()

# event loop and exit conditions (windows x click)
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            raise SystemExit

The Python function zip() can be used to transpose a twodimensional array (list of lists). The initial result would be a list of tuples, so a list comprehension is used to change the tuples to lists:

# transpose a 2D_array (list of lists) from 4x6 to 6x4

arr_4x6 = [
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 0],
[0, 0, 0, 1, 1, 0],
[0, 1, 0, 1, 1, 0],
]

# the * unpacks the array
arr_6x4 = [list(q) for q in zip(*arr_4x6)]

for row in arr_4x6:
    print(row)

print('-'*20)

for row in arr_6x4:
    print(row)

"""
my transpose result -->
[0, 0, 0, 0, 0, 0]
[0, 1, 1, 1, 1, 0]
[0, 0, 0, 1, 1, 0]
[0, 1, 0, 1, 1, 0]
--------------------
[0, 0, 0, 0]
[0, 1, 0, 1]
[0, 1, 0, 0]
[0, 1, 1, 1]
[0, 1, 1, 1]
[0, 0, 0, 0]
"""

A classic, Newton's method to estimate the square root of a number:

# estimate the square root of value v
# using Newton's Method

from math import sqrt

# value to estimate sqr for
v = 222

# initial guess
g = v/2.0

# loop n times
n = 7
for k in range(n):
    # Newton's method
    y = (g + v/g)/2.0
    g = y
    print( "%d) %0.8f  %0.8f  %0.8f" % (k+1, sqrt(v), g, sqrt(v)-g) ) 

"""
my output -->
1) 14.89966443  56.50000000  -41.60033557
2) 14.89966443  30.21460177  -15.31493734
3) 14.89966443  18.78102132  -3.88135690
4) 14.89966443  15.30073237  -0.40106795
5) 14.89966443  14.90492089  -0.00525646
6) 14.89966443  14.89966535  -0.00000093
7) 14.89966443  14.89966443  -0.00000000
"""

Before Python 3.0 the wrapper Tkinter.py was called when you used 'import Tkinter'. Now Tkinter has followed wx, and turned into a more modern package approach with a directory named tkinter that uses _init__.py as the wrapper, which means you have to use 'import tkinter'. Here is an example:

# draw a circle with given center (x,y) and radius
# notice that Python25 uses 'Tkinter' and Python30 'tkinter'

# comment/uncomment for the correct Python version
# for Python25 use
#import Tkinter as tk
# for Python30 use
import tkinter as tk

def get_center(x1, y1, x2, y2):
    '''
    for a rectangle with ulc=(x1,y1) and lrc=(x2,y2)
    calculate the center (x,y)
    '''
    x = x1 + (x2 - x1)//2
    y = y1 + (y2 - y1)//2
    return x, y
    
def get_square(x, y, radius):
    '''
    given the center=(x,y) and radius
    calculate the square for the circle to fit into
    return x1, y1, x2, y2 of square's ulc=(x1,y1) and lrc=(x2,y2)
    '''
    x1 = x - radius
    y1 = y - radius
    x2 = x + radius
    y2 = y + radius
    return x1, y1, x2, y2

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

# create a canvas to draw on
cv = tk.Canvas(root, width=300, height=300, bg='white')
cv.grid()

# draw a circle with given center (x,y) and radius
x, y = 150, 120
radius = 65
# to draw a circle you need to get the ul and lr corner coordinates
# of a square that the circle will fit inside of
rect = get_square(x, y, radius)
# draw the cicle that fits into the rect/square
# default fill is canvas bg
#cv.create_oval(rect)
circle1 = cv.create_oval(rect, fill='red')

# testing ...
print(get_square(x, y, radius))  # (10, 10, 90, 90)
print(get_center(*rect))   # (50, 50)
print(cv.coords(circle1))  # [10.0, 10.0, 90.0, 90.0] 

# start the event loop
root.mainloop()

Here we develop the concept of a standard deviation of a set of numbers following the steps outlined in the wikipedia reference. Python is really well suited for that sort of thing ...

# Suppose we wished to find the standard deviation of the data set
# consisting of the values 3, 7, 17, and 19
q = [3, 7, 17, 19]

# Step 1: find the arithmetic mean (average) of 3, 7, 17, and 19
avg = float(sum(q))/len(q)
print(avg)  # --> 11.5
 
# Step 2: find the deviation of each number from the mean or avg
dev = []
for x in q:
    dev.append(x - avg)
print(dev)  # --> [-8.5, -4.5, 5.5, 7.5]

# Step 3: square each of the deviations,
# which amplifies large deviations and makes negative values positive
sqr = []
for x in dev:
    sqr.append(x * x)
print(sqr)  # --> [72.25, 20.25, 30.25, 56.25]
 
# Step 4: find the mean (average) of those squared deviations
mean = sum(sqr)/len(sqr)
print(mean)  # --> 44.75
 
# Step 5: take the square root of the quotient
# (converting squared units back to regular units)
standard_dev = mean**0.5
print( "the standard deviation of set %s is %f" % (q, standard_dev) )

"""
final result -->
the standard deviation of set [3, 7, 17, 19] is 6.689544
"""

This little code creates a list of all the files (full path) in a given directory and any of its subdirectories:

# create a list of all the files in a given direcory
# and any of its subdirectories (Python25 & Python30)

import os

def file_lister(currdir, mylist=[]):
    """
    returns a list of all files in a directory and any of
    its subdirectories
    note that default mylist becomes static
    """
    for file in os.listdir(currdir):
        # add directory to filename
        full_name = os.path.join(currdir, file)  
        if not os.path.isdir(full_name):
            mylist.append(full_name)
        else:
            # recurse into subdirs
            file_lister(full_name)
    return mylist

dir_name = r"C:\Python25\Tools" 
file_list = file_lister(dir_name)
for file in file_list:
    print(file)

"""
my partial output -->
C:\Python25\Tools\i18n\makelocalealias.py
C:\Python25\Tools\i18n\msgfmt.py
C:\Python25\Tools\i18n\pygettext.py
C:\Python25\Tools\pynche\ChipViewer.py
C:\Python25\Tools\pynche\ChipViewer.pyc
C:\Python25\Tools\pynche\ColorDB.py
...
...
"""

Is Python30 really slower than Python25?
I used a little timing decorator to give it a test:

# time relatively time consuming functions
# with a decorator function
# apply the decorator right above the function
# you want to time, starting with a @
# works with Python25 and Python30
# (use module timeit for faster function)

import time

def print_timing(func):
    """set up a decorator function for timing"""
    def wrapper(*arg):
        t1 = time.time()
        res = func(*arg)
        t2 = time.time()
        print('%s took %0.3f ms' % (func.__name__, (t2-t1)*1000.0))
        return res
    return wrapper

@print_timing
def get_primes(n):
    """
    standard optimized sieve algorithm to get a list
    of prime numbers from 2 to < n, prime numbers are
    only divisible by unity and themselves
    (1 is not considered a prime number)
    """
    if n < 2:  return []
    if n == 2: return [2]
    # do only odd numbers starting at 3
    s = list(range(3, n+1, 2))
    # n**0.5 simpler than math.sqr(n)
    mroot = n ** 0.5
    half = len(s)
    i = 0
    m = 3
    while m <= mroot:
        if s[i]:
            j = (m*m-3)//2
            s[j] = 0
            while j < half:
                s[j] = 0
                j += m
        i += 1
        m = 2*i+3
    # skip zero items in list s
    return [2]+[x for x in s if x]


print( "prime numbers from 2 to <10,000,000 using a sieve algorithm")
prime_list = get_primes(10000000)
print('-'*50)
print("test print just the first 15 primes:")
print(prime_list[:15])
print("... and the last 5 primes:")
print(prime_list[-5:])

"""
my result with Python30 -->
prime numbers from 2 to <10,000,000 using a sieve algorithm
get_primes took 6296.000 ms
--------------------------------------------------
test print just the first 15 primes:
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]
... and the last 5 primes:
[9999937, 9999943, 9999971, 9999973, 9999991]

just a note, result with Python25 -->
get_primes took 5409.000 ms
"""

Want to know more about decorators, see:
http://www.siafoo.net/article/68

April 1 is just around the corner, and it has come to my attention that the brains behind MicroSoft have used this simple Python program to determine the release number of the next Windows version ...

# name the next Windows version ...

def next_version(release_list):
    j = ",".join(release_list)
    s = sum([x.isdigit() for x in j])
    return sum(map(int, str(s)))


release_list = ['1.0', '2.0', '2.1x', '3.0', '3.1', '3.5', '3.51',
    '4.0', '95', '98', 'ME', 'NT', '2000', 'XP', 'Vista']

print( "The next Windows version is %s" % next_version(release_list) )
commented: :) +14

The Tkinter GUI toolkit does not add a scrollbar to a listbox automagically, you have to do it with a few lines of extra code:

# simple example of a scrollable listbox for Tkinter
# for Python30 use 'import tkinter as tk'

import Tkinter as tk

root = tk.Tk()
root.title('a scrollable listbox')

# create the listbox (height/width in char)
listbox = tk.Listbox(root, width=50, height=6)
listbox.grid(row=0, column=0)

# create a vertical scrollbar to the right of the listbox
yscroll = tk.Scrollbar(command=listbox.yview, orient=tk.VERTICAL)
yscroll.grid(row=0, column=1, sticky='n'+'s')
listbox.configure(yscrollcommand=yscroll.set)

# now load the listbox with data
friend_list = [
'Stew', 'Tom', 'Jen', 'Adam', 'Ethel', 'Barb', 'Tiny', 
'Tim', 'Pete', 'Sue', 'Egon', 'Swen', 'Albert']
for item in friend_list:
    # insert each new item to the end of the listbox
    listbox.insert('end', item)

root.mainloop()

Want to use a nice file dialog window to open files for your console program? Here is a way:

# use Tkinter's file dialog window to get a file name
# with full path, that you can use in a console program
# askopenfilename() gives one selected filename

# with Python25 use ...
import Tkinter as tk
from tkFileDialog import askopenfilename

# with Python30 use ...
#import tkinter as tk
#from tkinter.filedialog import askopenfilename

root = tk.Tk()
# show askopenfilename dialog without the Tkinter window showing
root.withdraw()

# default is all files
file_name = askopenfilename()

# now you can use the file_name in your program
print(file_name)  # test

If you have .NET installed on your Windows machine, or Mono on your Linux machine you can use those libraries to run IronPython ...

# create a window with 2 buttons using ironpython
# experiment with events, colors, styles
# ironpython gives access to the Windows .NET or Linux Mono libraries
# download ironpython from:
# http://ironpython.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=12481
# tutorial at:
# http://www.zetcode.com/tutorials/ironpythontutorial/
#
# if ironpython is installed in 'C:\IronPython 2.0.1\' and you save this script
# as 'ip_Buttons2.py' in subdirectory 'Atest' then you can run it with command:
# C:\IronPython 2.0.1\ipy.exe C:\IronPython 2.0.1\Atest\ip_Buttons2.py

import clr

clr.AddReference("System.Windows.Forms")
clr.AddReference("System.Drawing")

from System.Windows.Forms import Application, Form, Button
from System.Windows.Forms import FlatStyle
from System.Drawing import Size, Point, Color

class IForm(Form):

    def __init__(self):
        # set form title, position, size, bachground color
        self.Text = 'Button'
        self.CenterToScreen()
        self.Size = Size(300, 150)
        self.BackColor = Color.Green

        btn1 = Button()
        btn1.Parent = self
        btn1.Text = "Quit"
        btn1.Location = Point(50, 30)
        btn1.BackColor = Color.Pink
        # click on the button to call btn1_OnClick()
        btn1.Click += self.btn1_OnClick

        btn2 = Button()
        btn2.Parent = self
        btn2.Text = "Press Me"
        btn2.Location = Point(50, 70)
        btn2.FlatStyle = FlatStyle.Popup
        btn2.BackColor = Color.Linen
        # click on the button to call btn2_OnClick()
        btn2.Click += self.btn2_OnClick

    def btn1_OnClick(self, sender, args):
        self.Close()

    def btn2_OnClick(self, sender, args):
        self.Text = 'btn2 pressed'
        # test information ...
        print sender
        print sender.Text, type(sender.Text)


Application.Run(IForm())

Familiar with C#? IronPython is basically Python, but has a little C# thrown in.

One way to approach multidimensional arrays in Python is to use a dictionary container with the index tuple as a key ...

# create a 3x4x2 3D-array using a dictionary with index tuples as keys
# initialize values to zero
arr3d = dict([((x,y,z), 0) for x in range(3) for y in range(4) 
    for z in range(2)])

# Python3 has dictionary comprehension to simplify this
#arr3d = {(x,y,z):0 for x in range(3) for y in range(4) for z in range(2)} 

# sorts the key index tuples
for ix in sorted(arr3d):
    print( "ix=%s val=%s" % (ix, arr3d[ix]) )

print('-'*20)

# change some values, basically assign to index
arr3d[2, 1, 0] = 5
arr3d[1, 0, 1] = 17
# or ...
ix = (0, 0, 0)
arr3d[ix] = 9
# or just ...
ix = 1, 1, 1
arr3d[ix] = 3

for ix in sorted(arr3d):
    print( "ix=%s val=%s" % (ix, arr3d[ix]) )
    
print('-'*20)

# get a specific value from a given index
print(arr3d[1, 1, 1])  # 3
# or ... 
ix = 0, 0, 0
print(arr3d[ix])  # 9

print('-'*20)

# get the lowest and highest key
low = (min(arr3d.keys()))    # --> (0, 0, 0) 
heigh = (max(arr3d.keys()))  # --> (2, 3, 1)
# show values
print( "ix=%s val=%s" % (low, arr3d[low]) )
print( "ix=%s val=%s" % (heigh, arr3d[heigh]) )

# get the heighest value in the array
print(max(arr3d.values()))  # 17

"""
my result -->
ix=(0, 0, 0) val=0
ix=(0, 0, 1) val=0
ix=(0, 1, 0) val=0
ix=(0, 1, 1) val=0
ix=(0, 2, 0) val=0
ix=(0, 2, 1) val=0
ix=(0, 3, 0) val=0
ix=(0, 3, 1) val=0
ix=(1, 0, 0) val=0
ix=(1, 0, 1) val=0
ix=(1, 1, 0) val=0
ix=(1, 1, 1) val=0
ix=(1, 2, 0) val=0
ix=(1, 2, 1) val=0
ix=(1, 3, 0) val=0
ix=(1, 3, 1) val=0
ix=(2, 0, 0) val=0
ix=(2, 0, 1) val=0
ix=(2, 1, 0) val=0
ix=(2, 1, 1) val=0
ix=(2, 2, 0) val=0
ix=(2, 2, 1) val=0
ix=(2, 3, 0) val=0
ix=(2, 3, 1) val=0
--------------------
ix=(0, 0, 0) val=9
ix=(0, 0, 1) val=0
ix=(0, 1, 0) val=0
ix=(0, 1, 1) val=0
ix=(0, 2, 0) val=0
ix=(0, 2, 1) val=0
ix=(0, 3, 0) val=0
ix=(0, 3, 1) val=0
ix=(1, 0, 0) val=0
ix=(1, 0, 1) val=17
ix=(1, 1, 0) val=0
ix=(1, 1, 1) val=3
ix=(1, 2, 0) val=0
ix=(1, 2, 1) val=0
ix=(1, 3, 0) val=0
ix=(1, 3, 1) val=0
ix=(2, 0, 0) val=0
ix=(2, 0, 1) val=0
ix=(2, 1, 0) val=5
ix=(2, 1, 1) val=0
ix=(2, 2, 0) val=0
ix=(2, 2, 1) val=0
ix=(2, 3, 0) val=0
ix=(2, 3, 1) val=0
--------------------
3
9
--------------------
ix=(0, 0, 0) val=9
ix=(2, 3, 1) val=0
17

"""

You can use the local dictionary vars() to introduce variables into strings ...

# using the local dictionary vars() to put
# variables into strings

name = "Harry"
name2 = "Verderchi"

for i in range(1, 5):
    # %d for integers and %s for strings
    print( "#%(i)d: %(name)s %(name2)s" % vars() )

"""
my result  -->
#1: Harry Verderchi
#2: Harry Verderchi
#3: Harry Verderchi
#4: Harry Verderchi
"""

String templating was introduced in Python 2.4 ...

# using string.Template() and the local dictionary vars()
# for formatted printing

import string

name = "Harry"
name2 = "Verderchi"

# create the template (note the $ before each variable name)
t = string.Template("#$i: $name $name2")

for i in range(1, 5):
    # use safe_substitute() for potential missing variables
    print( t.safe_substitute(vars()) )

"""
my output -->
#1: Harry Verderchi
#2: Harry Verderchi
#3: Harry Verderchi
#4: Harry Verderchi
"""

If you want to know what vars() looks like, just print it.

commented: Random rep for effort in this thread +17

This demonstrates a little function to extract the numeric value from a string like "$12.34/pound" where you want just 12.34 to do calculations:

# extract the numeric value from a data string
# snee

def extract_number(data_str):
    """
    extract the numeric value from a string
    the string should contain only one number
    return the number as int, float or None
    """
    s = ""
    for c in data_str:
        if c in '1234567890.-':
            s += c
    if s:
        # convert number to int or float
        return eval(s)
    else:
        return None


data_raw = """
header
23 bushels
 43 years old
4323 Maiden Lane
-$23.44/kg
 +$12.32
footer
"""

# create a list of the string data
data_list = data_raw.split('\n')
print(data_list)  # test

print('-'*60)

# extract numeric values from the data in the list
for data_str in data_list:
    print(extract_number(data_str))

"""
my result -->
['', 'header', '23 bushels', ' 43 years old', '4323 Maiden Lane',
'-$23.44/kg', ' +$12.32', 'footer', '']
------------------------------------------------------------
None
None
23
43
4323
-23.44
12.32
None
None
"""

For those of you who like to calculate in fractions:

# Python30 has a module fraction that allows you to
# calculate with fractions, the result is a fraction
# is more precise than using floating point numbers
# ene

from fractions import Fraction

# Fraction(numerator, denominator)
# for instance fraction 2/3 would be Fraction(2, 3)
a = Fraction(2, 3)
b = Fraction(2, 5)
c = Fraction(3, 7)

print( "%s + %s = %s" % (a, b, a + b) )
print( "%s + %s + %s = %s" % (a, b, c, a + b + c) )
print( "(%s + %s)/(%s) = %s" % (a, b, c, (a + b)/c) )

"""
my display -->
2/3 + 2/5 = 16/15
2/3 + 2/5 + 3/7 = 157/105
(2/3 + 2/5)/(3/7) = 112/45
"""

The latest Python version has added some candy:

# Python3.1 allows formatting of thousands
# and defaults format indexing in print()
# ene

n = 123456789
print(format(n, ',d'))

"""
my display -->
123,456,789
"""

m = 1234567.8912
print(format(m, ',.2f'))

"""
my display -->
1,234,567.89
"""

amount = format(1234567, ',d')
price = format(1234.56, ',.2f')
# note that {} defaults to the proper arg index
print('{} bottles at ${} each'.format(amount, price))

"""
my display -->
1,234,567 bottles at $1,234.56 each
"""

I have Python25, Python26, Python30, and Python31 installed on my homely Vista computer. To easily select which Python version to use I like the IDE Editra (wxPython based) and its Launch plugin.

Just a table of ASCII characters ...

# print a 16 column table of ASCII characters from 0 to 127

# dictionary of non-printable asccii characters
controls_dic = {
0: 'NUL', 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(0, 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
commented: very useful! +8
commented: great stuff +7

Floating point numbers are often close approximations of a value, very close, but approximations never the less. So if you directly compare floating point number results you can get surprises as shown here:

def fuzzyequals(a, b, delta=0.0000001):
    """
    returns true if a is between b-delta and b+delta
    used for comparison of floating point numbers a and b
    """
    return abs(a-b) < delta

a = 0.61
c = 0.49
b = 1.1 - c  # b should be 0.61

# fuzzy comparison
if fuzzyequals(a, b):
    print("fuzzy_true")
else:
    print("fuzzy_false")

# direct comparison
if a == b:
    print("direct_true")
else:
    print("direct_false")

# shows true floating point number representation
print("should be [0.61, 0.61, 0.49]")
print([a, b, c])

"""
my output -->
fuzzy_true
direct_false
should be [0.61, 0.61, 0.49]
[0.60999999999999999, 0.6100000000000001, 0.48999999999999999]
"""

In Python2.5 the range() function returns a list and the xrange() function an iterator (generator). Python 3.0 replaces range() with xrange() and now calls it range(). Anyway, range(start, stop, step) handles only integer values, and if you want to use floats, you have to role your own, as show in this example:

def frange(start=0, stop=0, step=1.0):
    """similar to xrange, but handles floating point numbers"""
    if step <= 0:
        while start > stop:
            yield start
            start += step
    else:
        while start < stop:
            yield start
            start += step

# testing ...
for x in frange(1.5, 4.7):
    print(x)

print("-"*20)

for x in frange(17, 4, -2.9):
    print(x)

print("-"*20)

for x in frange(stop=2.5, step=0.4):
    print(x)

print("-"*20)

print(list(frange(1.5, 5.2)))


"""
my output -->
1.5
2.5
3.5
4.5
--------------------
17
14.1
11.2
8.3
5.4
--------------------
0
0.4
0.8
1.2
1.6
2.0
2.4
--------------------
[1.5, 2.5, 3.5, 4.5]
"""

In the English language you can add a suffix to a number, so for instance first becomes 1st, second 2nd, third 3rd, fourth 4th and so on. Here is a little Python program that does it for you, and teaches a few list tricks too:

# add the proper suffix to integer numbers
# the suffix list index coincides with the number
# apply modulus 100 for numbers that exceed the list index
# snee

# list_0to9 also holds true for list_20to29 etc.
list_0to9 = ['th', 'st', 'nd', 'rd'] + ['th']*6
# 11th to 13th are exceptions
list_10to19 = ['th']*10

# suffix list for numbers 0 to 99
suffix_list = list_0to9 + list_10to19 + (list_0to9)*8

#print suffix_list

# test it
for x in range(1000):
    # use modulus 100 to recycle through the list
    # in case numbers exceed the list index
    print( "%d%s" % (x, suffix_list[x%100]) )

"""
part of my output -->
0th
1st
2nd
3rd
4th
5th
6th
7th
8th
9th
10th
11th
12th
13th
14th
15th
16th
17th
18th
19th
20th
21st
22nd
23rd
24th
25th
...
...
990th
991st
992nd
993rd
994th
995th
996th
997th
998th
999th
"""
commented: nice code indeed! +7

Starting with Python 2.5 the database module sqlite3 is part of the distribution. Once you start using sqlite3, you discover the world of database programs with their powerful query language. I have used capital letters for the query language part to make it stand out. Here is a simple example of sqlite3:

# test the sqlite3 module, write and read a database file
# note that Python 2.5 and higher versions have sqlite3 builtin
# sqlite3.connect(database, timeout=5.0, isolation_level=None,
#   detect_types=0, factory=100)
# timeout=5.0 --> allows multiple access for 5 seconds (for servers)
# isolation_level=None -->  autocommit mode
# detect_types=0 --> native types TEXT, INTEGER, FLOAT, BLOB and NULL
# factory=100 --> statement cache to avoid SQL parsing overhead
# tested with Python 2.5 and Python 3.0
# snee

import sqlite3

# create/connect to a permanent file database
#con = sqlite3.connect("my_db.db3")
# for temporary testing you can use memory only
con = sqlite3.connect(":memory:")

# establish the cursor, needed to execute the connected db
cur = con.cursor()

# create/execute a table:
cur.execute('CREATE TABLE IF NOT EXISTS clients \
    (id INT PRIMARY KEY, \
    firstname CHAR(60), \
    lastname CHAR(60))')

# insert several lines at once using a
# list of (id, firstname, lastname) tuples
# use try/except or the existing db will complain about
# the non-unique id since it is already in the db
try:
    clients = [
    (106, "Hugo", "Winterhalter"),
    (107, "Ella", "Fitzgerald"),
    (108, "Louis", "Armstrong"),
    (109, "Miles", "Davis")
    ]
    cur.executemany("INSERT INTO clients (id, firstname, lastname) \
        VALUES (?, ?, ?)", clients )
except:
    pass

# add another client
# again, use try/except or the existing db will complain about
# the non-unique id if it is already in the db
try:
    new_client = (110, "Benny", "Goodman")
    cur.execute("INSERT INTO clients (id, firstname, lastname) \
        VALUES (?, ?, ?)", new_client)
except:
    pass

# important if you make changes to the database
# commits current data to the db file (data is persistant now)
con.commit()

# now test it
# get data row by row
print("Show data row by row:")
# also tell it to sort/order data by lastname
cur.execute('SELECT id, firstname, lastname FROM clients \
    ORDER BY lastname')
for row in cur:
    print(row)

print('-'*40)

# select just one data item from each row ...
cur.execute('SELECT firstname FROM clients')
print(cur.fetchall())

print('-'*40)

# or ...
cur.execute('SELECT firstname FROM clients')
for row in cur:
    print(row[0])

print('-'*40)

# select a specific data row ...
cur.execute('SELECT * FROM clients WHERE lastname="Davis"')
print(cur.fetchall())

# finally ...
con.close()

"""
my output -->
Show data row by row:
(108, u'Louis', u'Armstrong')
(109, u'Miles', u'Davis')
(107, u'Ella', u'Fitzgerald')
(110, u'Benny', u'Goodman')
(106, u'Hugo', u'Winterhalter')
----------------------------------------
[(u'Ella',), (u'Louis',), (u'Miles',), (u'Benny',), (u'Hugo',)]
----------------------------------------
Ella
Louis
Miles
Benny
Hugo
----------------------------------------
[(109, u'Miles', u'Davis')]
"""
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.