ZZucker 342 Practically a Master Poster

Here is the modification of vegaseat's code that will work with both Python27 and Python32:

# create a sound file in AU format playing a sine wave
# of a given frequency, duration and volume
# vegaseat code modified to work with Python27 and Python32

from struct import pack
from math import sin, pi

def au_file(name='test.au', freq=440, dur=1000, vol=0.5):
    """
    creates an AU format sine wave audio file
    of frequency freq (Hz)
    of duration dur (milliseconds)
    and volume vol (max is 1.0)
    """
    fout = open(name, 'wb')
    # header needs size, encoding=2, sampling_rate=8000, channel=1
    fout.write(pack('>4s5L', '.snd'.encode("utf8"), 24, 8*dur, 2, 8000, 1))
    factor = 2 * pi * freq/8000
    # write data
    for seg in range(8 * dur):
        # sine wave calculations
        sin_seg = sin(seg * factor)
        val = pack('b', int(vol * 127 * sin_seg))
        fout.write(val)
    fout.close()
    print("File %s written" % name)


# test the module ...
if __name__ == '__main__':
    au_file(name='sound440.au', freq=440, dur=2000, vol=0.8)

    # if you have Windows, you can test the audio file
    # otherwise comment this code out
    import os
    os.startfile('sound440.au')
ZZucker 342 Practically a Master Poster

You go to the store to buy a pound of Tshibo Java, your favorite coffee beans. There you are confronted with a dilema, the usual pound container costs $10. But the store offers you a choice, a new container with 33% more beans for $10 or the one pound container for a 33% discount.

Write a Python program to figure out which deal is the best, or are they the same?

vegaseat commented: economics 101 +14
ZZucker 342 Practically a Master Poster

The Python function range() handles only integers. Here is a range generator that handles floats:

# a floating point range generator with roundoff-fix
# works with Python2 and Python3

def frange(start, stop=None, step=1.0, delta=0.0000001):
    """
    a range generator that handles floating point numbers
    uses delta fuzzy logic to avoid float rep errors
    eg. stop=6.4 --> 6.3999999999999986 would slip through
    """
    # if start is missing it defaults to zero
    if stop == None:
        stop = start
        start = 0
    # allow for decrement
    if step <= 0:
        while start > (stop + delta):
            yield start
            start += step
    else:
        while start < (stop - delta):
            yield start
            start += step

# testing ...
# expect numbers 6.0 to 6.3
for k in frange(6.0, 6.4, 0.1):
    print("%f" % k)

'''my result -->
6.000000
6.100000
6.200000
6.300000   okay!
'''
ZZucker 342 Practically a Master Poster

One way to get your IP:

# get your ip
# Python32

import urllib.request

def get_external_ip():
    '''returns a string'''
    url = "http://automation.whatismyip.com/n09230945.asp"
    ipb = urllib.request.urlopen(url).read()
    # decode <class 'bytes'> to string
    ip = ipb.decode("utf8")
    return ip

print(get_external_ip())
ZZucker 342 Practically a Master Poster
# bubble sort a list in either direction

def bubblesort2(q):
    """
    test the bubble sort of a list of numbers
    returns asc and des lists
    asc is the list in ascending order
    des is the list in descending order
    """
    # make copies of the list
    asc = list(q)
    des = list(q)
    for passes in range(len(q)-1, 0, -1):
        for index in range(passes):
            # ascending order
            if asc[index] > asc[index + 1]:
                # do a tuple swap
                asc[index], asc[index + 1] = asc[index + 1], asc[index]
            # descending order
            if des[index] < des[index + 1]:
                des[index], des[index + 1] = des[index + 1], des[index]
    return asc, des

mylist = [4, 2, 7, 9, 25]
asc_list, des_list = bubblesort2(mylist)

print("original  : %s" % mylist)
print("ascending : %s" % asc_list)
print("descending: %s" % des_list)

'''
original  : [4, 2, 7, 9, 25]
ascending : [2, 4, 7, 9, 25]
descending: [25, 9, 7, 4, 2]
'''
ZZucker 342 Practically a Master Poster
# create an acronym

str1 = "Senior health inFormation development"

# just in case it isn't all lower case
str2 = str1.lower()

# make a title-cased copy
str3 = str2.title()

# now build the acronym from the capitalized letters
str4 = ""
for char in str3:
    if char.isupper():
        str4 += char

print("Original string : %s" % str1)
print("All lower case  : %s" % str2)
print("All words titled: %s" % str3)
print("Simple acronym  : %s" % str4)

'''
Original string : Senior health inFormation development
All lower case  : senior health information development
All words titled: Senior Health Information Development
Simple acronym  : SHID
'''
ZZucker 342 Practically a Master Poster

The proper way to save a dictionary object is with Python module pickle. Here is an example:

# use module pickle to save/dump and load a dictionary object
# or just about any other intact object
# use modes "wb" and "rb" to work with Python2 and Python3

import pickle

# create the test dictionary
before_d = {}
before_d[1]="Name 1"
before_d[2]="Name 2"
before_d[3]="Name 3"

# pickle dump the dictionary to a file
fout = open("dict1.dat", "wb")
pickle.dump(before_d, fout)
fout.close()

# pickle load the dictionary from a file
fin = open("dict1.dat", "rb")
after_d = pickle.load(fin)
fin.close()

print(before_d)  # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
print(after_d)   # {1: 'Name 1', 2: 'Name 2', 3: 'Name 3'}
HiHe commented: nice +4
ZZucker 342 Practically a Master Poster

I love yogurt, particularly Greek yogurt!

I agree that most newscasters need stuff thrown at them, but why waste good yogurt?

ZZucker 342 Practically a Master Poster

Time just keeps on going! Procrestinate now and slow it down a little!

ZZucker 342 Practically a Master Poster

To run a timer in the background you have to use the module threading.
You can also use the current time at start and end of the game and calculate the difference.

time elapsed using time.clock() or time.time():
 import time



# time.clock() is for windows only, updates every 1 ms
start = time.clock()

# your program code here ...

# for instance this demo code will take about 7.5 seconds
print "going"
time.sleep(2.5)  # 2.5 seconds
print "still going"
time.sleep(2.5)
print "still going"
time.sleep(2.5)
print "done"


# ... your program ends
end = time.clock()
print "Time elapsed = ", end - start, "seconds"
vegaseat commented: that's it +14
ZZucker 342 Practically a Master Poster

Select multiple items from a Tkinter list box:

# a simple Tkinter Listbox example
# press the shift or ctrl key to select multiple items

try:
    # for Python2
    import Tkinter as tk
except ImportError:
    # for Python3
    import tkinter as tk


def get_list():
    """
    function to read the listbox selection(s)
    (mutliple lines can be selected)
    and put the result(s) in a label
    """
    # tuple of line index(es)
    sel = listbox.curselection()
    # get the text, might be multi-line
    seltext = '\n'.join([listbox.get(x) for x in sel])
    label_text.set(seltext)

root = tk.Tk()
# used for label text
label_text = tk.StringVar(root)

# extended mode allows CTRL or SHIFT mouse selections
listbox = tk.Listbox(root, selectmode=tk.EXTENDED)
listbox.pack()

# click the button to show the selection(s)
button = tk.Button(root, text="Get Selection(s)", command=get_list)
button.pack()

# used to display selection(s)
label = tk.Label(root, textvariable=label_text)
label.pack()

# load some datalines into the listbox
items = ["one", "two", "three", "four", "five", "six"]
for item in items:
    listbox.insert(tk.END, item)

# highlight/preselect line 3 of listbox (starts with zero)
# lb.selection_set(first, last=None) can preselect more than 1 line
listbox.selection_set(3)

root.mainloop()
ZZucker 342 Practically a Master Poster

Use some of the financial formulas found at
http://www.math4finance.com/financial-formulas.php
to write Python programs to get monthly payment schedules,
future and present values, payment calculations and due dates.

ZZucker 342 Practically a Master Poster

Never knew you even existed.
You latest avatar sound a bit childish, how old are you?

ZZucker 342 Practically a Master Poster

Radish sprouts are popular in Japan. In 1996 there was an E. coli outbreak that killed 12 people and reportedly sickened more than 12,000 others. Commercially these sprouts are grown at about 100 degree F (38 degree C), a temperature ideal for the growth of E. coli bacteria.

ZZucker 342 Practically a Master Poster

Compare module re (regex) with some of the Python builtin string functions.

For instance:

import re

# wisdom from Mark Twain
text = '''
When your friends begin to flatter you on how young
you look, it's a sure sign you're getting old.
'''

searched = re.search("flat", text)
if searched.group(0):
    print("found '%s'" % searched.group(0)) 
    start, end = searched.span()
    print("at text index start = %d, end = %d" % (start, end))

""" my result is >>
found 'flat'
at text index start = 28, end = 32
"""

Python has a function find() that would work similarly.

What would you do if the text had several sub-strings you were searching for?

ZZucker 342 Practically a Master Poster

Polls show that the Palin/McCain ticket is closing the gab rapidly and Obama is only a few percent ahead now. This is largely due to voters discovering that Sarah Palin has a heart of gold and means what she says.

She protects the unborn.
She will bring back family values.
Make sure that every child has a father.
She will not take away our guns.
She is pro Christianity.
She supports the all important creation approach.
She will ban witchcraft.
She will not tax away your wealth.
Enemies of the US better be worried.
Countries that are not with us will suffer.
She will get and kill Osama.
She will make hockey the true American sport it is.

Ezzaral commented: Hehehe, quite amusing :) +13
ZZucker 342 Practically a Master Poster

Yeah vega, VPython is an interesting module for 3D modeling (free too). I played around with it and came up with this:

import visual as vs

vs.scene.width = 500
vs.scene.height = 500
vs.scene.title = "draw a cone on a ring (drag with right mouse button)"
# avoid autoscale (autoscale default=True)
vs.scene.autoscale = False

ring = vs.ring(pos=(0,0,0), axis=(8,0,-3), radius=5)
ring.color = (1.0, 1.0, 0.5)
# thickness of ring by default is 1/10th of radius
ring.thickness = 0.3

cone = vs.cone(pos=(0,5.7,0), axis=(0,-1,0), radius=1.8)
cone.color = (0.75, 1.0, 0.2)
Gribouillis commented: wow! +1
ZZucker 342 Practically a Master Poster

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
ZZucker 342 Practically a Master Poster

Most of you know the song

99 bottles of beer on the wall,
99 bottles of beer!
Take one down, pass it around,
98 bottles of beer on the wall!

98 bottles of beer on the wall,
98 bottles of beer!
Take one down, pass it around,
97 bottles of beer on the wall!

...
...

2 bottles of beer on the wall,2 bottles of beer!
Take one down, pass it around,
1 bottle of beer on the wall!

1 bottle of beer on the wall,
1 bottle of beer!
Take one down, pass it around,
No more bottles of beer on the wall!

Your mission is to write the entire lyrics of this song using a Python for loop.

ZZucker 342 Practically a Master Poster

"Please don't eat me! I have a wife and kids. Eat them!"
No, it was not GWB that said this, but Homer Simpson

ZZucker 342 Practically a Master Poster

Lardmeister. :icon_lol:

Now that is a disgusting thing to use against a good member of DaniWeb! I think Lardmeister needs to use my signature to object to that sort of foul underhanded stuff.

Dave Sinkula commented: True. I guess I acted hastily to a seemingly nonstop enslaught of trolling one-liners that have been pointed at least indirectly at me for the past year. Mea culpa. +16
ZZucker 342 Practically a Master Poster

One day at a local buffet, a man suddenly jumped up and called out, "My son is choking! He swallowed a quarter! Help! Please, anyone! Help! Help him!"

A man from a nearby table stood up and announced that he was quite experienced at this sort of thing. He stepped over with almost no look of concern at all, wrapped his hands around the boy's balls and squeezed very hard. Out popped the quarter. The man then went back to his table as though nothing had happened.

"Thank you! Thank you! Thank you!" the father cried. "Are you a paramedic?"

"No," replied the man, "I work for the Internal Revenue Service."

~s.o.s~ commented: Haha :-D +23
ZZucker 342 Practically a Master Poster

You know you're in love when you can't fall asleep because reality is finally better than your dreams.

murderotica commented: I do agree my dear. +1
ZZucker 342 Practically a Master Poster

Knowledge of foreign stuff is important!

Ancient Dragon commented: LOL :) +36
ZZucker 342 Practically a Master Poster

Ohio is listed as the 17th state in the U.S., but technically it is Number 47. Until August 7, 1953, Congress forgot to vote on a resolution to admit Ohio to the Union.

Now to something really funny:

One weekend, the husband is in the bathroom shaving when the kid he hired to mow his lawn, a local kid named Bubba, comes in to pee. The husband slyly looks over and is shocked at how immensely endowed Bubba is. He can't help himself, and asks Bubba what his secret is.

"Well," says Bubba, "every night before I climb into bed with a girl, I whack my dick on the bedpost three times. It works, and it sure impresses the girls!"

The husband was excited at this easy suggestion and decided to try it that very night. So before climbing into bed with his wife, he took out his organ and whacked it three times on the bedpost. His wife, half-asleep, said, "Bubba? Is that you?"

sittas87 commented: lol +2
tiger86 commented: OMG! That is like the funniest thing ever I printed it out gave it to a friend and they cracked up! +1
ZZucker 342 Practically a Master Poster

Let's put some bigotry on the other shoe:

What is the difference between a man and a government bond?
Bonds mature

What did God say after creating man?
I can do better

What do you call a man with half a brain?
Gifted

What does a man consider as a 7 course meal?
A hot dog and a six pack

How are men and parking spots alike?
The good ones are taken and what's left is handicapped

jasimp commented: hehe :) +8
ZZucker 342 Practically a Master Poster

Research shows that one in seven Americans do not own a cell phone.

Those are the people who actually drive in the proper lane.

Nick Evan commented: haha :D +8
ZZucker 342 Practically a Master Poster

This short code sample shows how to add an exit confirm to your wxPython program, from either a menu exit or the title bar exit:

# confirm exit of a wxPython program

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, mytitle, mysize):
        wx.Frame.__init__(self, parent, wx.ID_ANY, mytitle, size=mysize)

        # create a status bar at the bottom
        self.CreateStatusBar()
        self.SetStatusText("Click on File")

        menu = wx.Menu()
        # just one item to test exit confirm
        # the optional & allows you to use alt/x
        # the last string argument shows in the status bar on mouse_over
        menu_exit = menu.Append(wx.ID_ANY, "E&xit", "Exit the program")

        # create a menu bar at the top
        menuBar = wx.MenuBar()
        # the & allows you to use alt/f
        menuBar.Append(menu, "&File")
        self.SetMenuBar(menuBar)

        # bind the menu events to an action
        self.Bind(wx.EVT_MENU, self.onMenuExit, menu_exit)
        # responds to exit symbol x on frame title bar
        self.Bind(wx.EVT_CLOSE, self.onCloseWindow)

    def onMenuExit(self, event):
        # triggers wx.EVT_CLOSE event and hence onCloseWindow()
        self.Close(True)

    def onCloseWindow(self, event):
        # dialog to verify exit
        dlg = wx.MessageDialog(self, "Want to exit?", "Exit",
            wx.YES_NO|wx.ICON_QUESTION)
        if dlg.ShowModal() == wx.ID_YES:
            self.Destroy()
        dlg.Destroy()


app = wx.App(0)
# create the MyFrame instance and then show the frame
MyFrame(None, 'Confirm exit', (400, 300)).Show()
app.MainLoop()

Zoe

ZZucker 342 Practically a Master Poster

This might be the simplest way to display an image from a file using the wxPython GUI toolkit:

# simplest way to show an image from a file with wxPython

import wx

app = wx.App(0)
frame = wx.Frame(None, -1, "Show an image file")

# pick an image file you have in the working folder
# (can be a .jpg, .png, ,gif, .bmp image file)
image_file = 'clouds.jpg'
# create an internal image
image = wx.Bitmap(image_file)
# show the image as static bitmap
wx.StaticBitmap(frame, -1, image)

frame.Show()
app.MainLoop()

What the heck, lets make it even simpler:

import wx

app = wx.App(0)
frame = wx.Frame(None, -1, "Show an image file")
wx.StaticBitmap(frame, -1, wx.Bitmap('clouds.jpg'))
frame.Show()
app.MainLoop()
ZZucker 342 Practically a Master Poster

Some heavier wxPython stuff. I was playing around with the wx.ListCtrl() widget, and it took me quite a while to find a way to get a hold of the selected row. Here is a short example of the solution:

# exploring wxPython's
# wx.ListCtrl(parent, id, pos, size, style)
# a fancier list box with a lot of mix-in options
# some of the styles =
# wxLC_REPORT  report mode
# wxLC_HRULES  draws horizontal rules between rows in report mode
# wxLC_VRULES  draws vertical rules between columns in report mode.

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, data):
        # use default size and position
        wx.Frame.__init__(self, parent, wx.ID_ANY,
            'Test the wx.ListCtrl()',
            size=(400, 220))
        self.SetBackgroundColour("yellow")
        # make data available to the instance
        self.data = data

        # create the list control
        self.lc = wx.ListCtrl(self, wx.ID_ANY, size=(-1, 120),
             style=wx.LC_REPORT|wx.SUNKEN_BORDER|wx.LC_HRULES)
        # select an item (left mouse click on it) and bind to an action
        self.lc.Bind(wx.EVT_LIST_ITEM_SELECTED,self.onAction)

        self.loadList()

        # create an output widget
        self.label = wx.StaticText(self, wx.ID_ANY, "Select a name")

        # use a vertical boxsizer for the widget placement
        sizer_v = wx.BoxSizer(wx.VERTICAL)
        sizer_v.Add(self.lc, 1, flag=wx.ALL|wx.EXPAND, border=10)
        sizer_v.Add(self.label, 0, flag=wx.ALL|wx.EXPAND, border=10)
        self.SetSizer(sizer_v)

    def loadList(self):
        # first the columns with header titles
        self.lc.InsertColumn(0,"Name")
        self.lc.SetColumnWidth(0, 200)
        self.lc.InsertColumn(1,"Age",wx.LIST_FORMAT_RIGHT)
        self.lc.InsertColumn(2,"Weight",wx.LIST_FORMAT_RIGHT)

        # now each data row
        for key, val in self.data.items():
            # set max_rows, change if need be
            max_rows = 1000
            # also sets/updates row index starting at 0
            index = self.lc.InsertStringItem(max_rows, val[0])
            self.lc.SetStringItem(index, 1, val[1])
            self.lc.SetStringItem(index, 2, val[2])
            # needed by GetItemData()
            self.lc.SetItemData(index, key)

    def onAction(self, event):
        """ some action code"""
        # …
ZZucker 342 Practically a Master Poster

Some light wxPython stuff. The first example shows you how to bring in your own icon in the title of a frame:

# set the icon of a wx.Frame()

import wx

app = wx.App(0)

frame = wx.Frame(None, wx.ID_ANY, title='Set A New Icon')
# pick an icon image file you have ...
frame.SetIcon(wx.Icon('py.ico', wx.BITMAP_TYPE_ICO))
frame.Center()
frame.Show()
app.MainLoop()

The second example uses the wx.EVT_SIZE event to respond to changes in the size of the frame:

# use the wx.EVT_SIZE event to show the frame size
# the title itself may take up 34 pixels of the height

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent):
        # use default size and position
        wx.Frame.__init__(self, parent, wx.ID_ANY)
        self.SetBackgroundColour("yellow")
        wx.StaticText(self, wx.ID_ANY, "change the size of the frame", (5,5))

        # respond to changes in the size of the frame
        self.Bind(wx.EVT_SIZE, self.onSize)

    def onSize(self, event):
        """display the current frame size in the title"""
        self.SetTitle(str(event.GetSize()))  # eg. (400, 489)


app = wx.App(0)
# create a MyFrame instance and show the frame
MyFrame(None).Show()
app.MainLoop()
ZZucker 342 Practically a Master Poster

An interesting way to check if a letter is between A and Z:

def has_cap(text):
    """return True if text contains a capital letter"""
    for ch in text:
        # character ch is between A and Z inclusive
        if 'A' <= ch <= 'Z':
            return True
    return False

text1 = 'the Good die young, Pricks live forever!'
text2 = 'the good die young, pricks live forever!'
print 'text1 =', text1 
print 'text2 =', text2

# test the function has_cap()
if has_cap(text1):
    print "text1 has a capital letter"
else:
    print "text1 has no capital letter"

if has_cap(text2):
    print "text2 has a capital letter"
else:
    print "text2 has no capital letter"
ZZucker 342 Practically a Master Poster

I took the above wxPython templet and added a background or splash image. So now you have a templet that shows you how to create a frame, a panel, a label, an entry (input), a button, sizers, a multiline display and show an image. Could be the backbone of many wxPython GUI applications:

# basic wx.Frame with splash image panel (panel needed for sizers)
# label, edit, button, display, sizer, and border sizer

import wx

class MyFrame(wx.Frame):
    """
    frame and panel
    panel is neded for any sizer widgets
    """
    def __init__(self, parent, id, title):
        # this will be self
        wx.Frame.__init__(self, parent, id, title)
        # add panel
        panel = wx.Panel(self, -1)
        
        # pick a splash image file you have in the working folder
        image_file = 'HIVirus1.jpg'
        bmp = wx.Bitmap(image_file)
        # allow for alternative if splash image file not found
        if bmp:
            splash = wx.StaticBitmap(panel, -1, bmp)
        else:
            panel.SetBackgroundColour('green')
            splash = panel

        # now add the needed widgets
        self.label1 = wx.StaticText(splash, -1, 'Enter ... :')
        self.entry1 = wx.TextCtrl(splash, -1, '...')
        self.button1 = wx.Button(splash, -1, 'Do ... ')
        self.button1.SetBackgroundColour('yellow')
        self.button1.Bind(wx.EVT_BUTTON, self.onCmd)
        info = "Optional instructive message!"
        self.display = wx.TextCtrl(splash, -1, info, size=(250, 100), 
            style=wx.TE_MULTILINE)
        
        # use gridbagsizer for layout of widgets
        # set optional vertical and horizontal gaps
        sizer = wx.GridBagSizer(vgap=5, hgap=10)
        sizer.Add(self.label1, pos=(0, 0))       # pos(row,column)
        sizer.Add(self.entry1, pos=(0, 1))  # row 0, column 1

        # span=(1, 2) --> allow to span over 2 columns 
        sizer.Add(self.button1, pos=(1, 0), span=(1, 2))
        sizer.Add(self.display, pos=(2, 0), span=(1, 2))
        
        # use boxsizer to add border around …
sneekula commented: nicely orchestrated +4
ZZucker 342 Practically a Master Poster

I took Lardmeister's code and made a generic wxPython templet that you can then flesh out for cases when you need the user to enter data, press a button to process the data, and then show the result in an output area:

# basic wx.Frame with panel (needed for sizers), label, 
# edit, button, display, sizer, and border sizer

import wx

class MyFrame(wx.Frame):
    """
    frame and panel
    panel is neded for any sizer widgets
    """
    def __init__(self, parent, id, title):
        # this will be self
        wx.Frame.__init__(self, parent, id, title)
        # add panel
        panel = wx.Panel(self, -1)
        panel.SetBackgroundColour('green')

        # now add the needed widgets
        self.label1 = wx.StaticText(panel, -1, 'Enter ... :')
        self.entry1 = wx.TextCtrl(panel, -1, '...')
        self.button1 = wx.Button(panel, -1, 'Do ... ')
        self.button1.SetBackgroundColour('yellow')
        self.button1.Bind(wx.EVT_BUTTON, self.onCmd)
        info = "Optional instructive message!"
        self.display = wx.TextCtrl(panel, -1, info, size=(250, 100), 
            style=wx.TE_MULTILINE)
        
        # use gridbagsizer for layout of widgets
        # set optional vertical and horizontal gaps
        sizer = wx.GridBagSizer(vgap=5, hgap=10)
        sizer.Add(self.label1, pos=(0, 0))       # pos(row,column)
        sizer.Add(self.entry1, pos=(0, 1))  # row 0, column 1

        # span=(1, 2) --> allow to span over 2 columns 
        sizer.Add(self.button1, pos=(1, 0), span=(1, 2))
        sizer.Add(self.display, pos=(2, 0), span=(1, 2))
        
        # use boxsizer to add border around sizer
        border = wx.BoxSizer()
        border.Add(sizer, 0, wx.ALL, 20)
        panel.SetSizerAndFit(border)
        self.Fit()
        
    def onCmd(self, event):
        """process data and show result"""
        # get the data from the input widget
        string1 = self.entry1.GetValue()
        # do the processing ...
        proc_data = string1 * 3   
        # show the result ...
        self.display.SetValue(proc_data) 
        

app = wx.App(redirect=False)
frame = MyFrame(None, -1, "Title …
ZZucker 342 Practically a Master Poster

Looking for a male couch/mouse potato with a large beer belly and a minor amount of hair on top, should be ugly enough to scare any insects out of my place.

jephthah commented: snicker +3
ZZucker 342 Practically a Master Poster

Welcome to the world of self! Just a side note, the Python style guide recommends to start class names with upper case and function/method names with lower case. If you write larger programs, this really helps.

The Python style guide by GVR himself:
http://www.python.org/peps/pep-0008.html

ZZucker 342 Practically a Master Poster

Eating a large amount of beans and then do one or more of the following:
Take a bubble bath.
Get my teeth checked at the dentist.
Go to an IRS audit.
Go to jury duty.

scru commented: LOL +3
majestic0110 commented: Hehe +2
ZZucker 342 Practically a Master Poster

Just a basic Python class example to show you how you can work with it:

# basic experiments with Python class

class Cat(object):
    # this is public
    cost = 100
    # this is private to the class
    __price = cost + cost * 0.25  
    # constructor
    def __init__(self, num=1):
        self.num = num
        self.sound = "meow " * self.num
        print self.sound
 
    def own(self):
        print "I own", self.num, "cats"

    def paid(self):
        self.total = self.__price * self.num
        print "I paid", self.total, "for my cats"
        
    def kitten(self):
        self.kit = 5
        print "One cat just had", self.kit, "kittens"
        return self.kit


class Dog(object):
    # this is public
    cost = 400
    # this is private to the class
    __price = cost + cost * 0.25  
    # constructor
    def __init__(self, num=1):
        self.num = num
        self.sound = "woof " * self.num
        print self.sound

    def own(self):
        print "I own", self.num, "dogs"

    def paid(self):
        self.total = self.__price * self.num
        print "I paid", self.total, "for my dogs"
        

class Pets(Cat, Dog):
    """class Pets inherits class Cat and class Dog"""
    # constructor
    def __init__(self):
        self.num = cat.num + dog.num
        self.sound = cat.sound + dog.sound 
        print self.sound

    def own(self):
        print "I own", self.num, "pets"

    def paid(self):
        print "I paid", dog.total + cat.total, "for my pets"
        
    def update(self):
        # notice how Pets inherited kitten() from class Cat
        self.kit = self.kitten()
        print "So now I have", self.num + self.kit, "pets"


cat = Cat(3)
cat.own()
cat.paid()

print '-'*30

dog = Dog(2)
dog.own()
dog.paid()

print '-'*30

pets = Pets()
pets.own()
pets.paid()

print '-'*30

pets.update()

"""
my output --> …
vegaseat commented: very nice example +8
ZZucker 342 Practically a Master Poster

If you make a copy of a list, and you have a nested list or don't know what the list might be in the your program, always use module copy:

# make a true copy of a nested list

import copy

nested_list = [1, [2, 3], 4]
copied_list = copy.deepcopy(nested_list)

# a regular list copy looks alright at first
copied_list2 = nested_list[:]

print nested_list   # [1, [2, 3], 4]
print copied_list   # [1, [2, 3], 4]
print copied_list2  # [1, [2, 3], 4]

print '-'*20

# change the orignal list
nested_list[1][0] = 99

# but the test shows a surprise!
print nested_list   # [1, [99, 3], 4]
print copied_list   # [1, [2, 3], 4]
# with simple copy the inner list is just an alias 
print copied_list2  # [1, [99, 3], 4]  oops!
ZZucker 342 Practically a Master Poster

In an ugly and unhappy world the richest man can purchase nothing but ugliness and unhappiness.
-- George Bernard Shaw

thunderstorm98 commented: Nice one.. +3
ZZucker 342 Practically a Master Poster

You cannot use the line:

if sex == "M" or "m":

In Python you have to write it this way:

if sex == "M" or sex == "m":

Actually you might just use:

if sex in ["M", "m"]:
gwarguy commented: Thanks for explaining my problem in a clear manner as fit to my little or no experience:) +1
ZZucker 342 Practically a Master Poster

Ancient Dragon:
AD's opinions are exactly the same as my grandpa Simon's. So I imagine him to be a friendly little old wise man with a billiard ball head.

ZZucker 342 Practically a Master Poster

Give a man a fire and he's warm for a day, but set his soul on fire and he's warm for the rest of his life.

thunderstorm98 commented: Nice One... +3
ZZucker 342 Practically a Master Poster

jbennet:
The real computer genius here. Never gives you an old and stale idea or opinion. His only challenge is the English language, probably because he is Scottish. I don't know what the native language of Scottland is?

ZZucker 342 Practically a Master Poster

Here is a small dictionary of food items and their calories. The portion amounts vary all over the map. Convert all calories for a 1 oz portion or, if you desire, a 100 gram portion (1 oz = 28.35 grams):

# a dictionary of {food_name:[amount, calories], ...}
food = {
"pastrami": ["2 oz", 170],
"meatloaf": ["3 oz", 315],
"veal": ["3.5 oz", 190],
"beef": ["2 oz", 310],
"venison": ["4 oz", 225],
"potato": ["8 oz", 100],
"spinach": ["8 oz", 45],
"tomato": ["8 oz", 45],
"egg plant": ["3.5 oz", 25],
"cauliflower": ["8 oz", 35],
"butter": ["1 oz", 200],
"cheddar": ["1 oz", 115],
"swiss": ["1 oz", 105],
"egg": ["2 oz", 80]
}
ZZucker 342 Practically a Master Poster

There are more rings in America than there are fingers.

ZZucker 342 Practically a Master Poster

If you just want to count the words, lines and characters in a text file, Python offers an elegant solution:

# find the number of lines, words and characters in a text file

# these are the counters, start at zero
number_lines = 0
number_words = 0
number_characters = 0

# pick a text file you have
filename = 'my_text.txt'
for line in file(filename):
    # update the counters
    number_lines += 1
    number_words += len(line.split())
    number_characters += len(line)
    
print filename, 'has:'
print number_lines, 'lines'
print number_words, 'words'
print number_characters, 'characters'

Thanks to bgeddy for his inspiring pseudo code.

vegaseat commented: Another example of clean code +8
ZZucker 342 Practically a Master Poster

The largest cucumber ever harvested weighed in at 8.4 kg.

Note:
Sorry, I was wrong with the full moon. The February months of 1866, 1885, 1915, 1934, 1961 did not have a full moon.

ZZucker 342 Practically a Master Poster

The simplest way, but maybe not the most efficient for large files, is this:

# sample text for testing
# could come from a text file read like this:
"""
infile = open("my_text.txt","r")
text = infile.read()
infile.close()
"""

text = """\
My name is Fred Flintstone and I am a famous TV
star.  I have as much authority as the Pope, I
just don't have as many people who believe it.
"""

search = "Fred"
index = text.find(search)
print search, "found at index", index

"""
my ouput (index is zero based) -->
Fred found at index 11
"""

Note that find() only finds the first occurrence of the search word!

ZZucker 342 Practically a Master Poster

Another word frequency program, but this time we want ot create a dictionary of provider:frequency pairs from a number of given email addresses:

# count the frequency of providers from a number of given emails

emails = """\
manolis@gmail.com
giannis@gmail.com
kostas@yahoo.com
eirini@yahoo.com
ssss@aol.com
wertza@yahoo.gr
xristhanthi@gmail.com
"""

# split into list of lines (individual email)
lines = emails.split()

provider_freq = {}
for item in lines:
    # split each line item at the @ character
    user, provider = item.split('@')
    #print user, provider  # test
    # build the dictionary
    count = provider_freq.get(provider, 0)
    provider_freq[provider] = count + 1
    
print provider_freq

"""
my output -->
{'yahoo.com': 2, 'aol.com': 1, 'gmail.com': 3, 'yahoo.gr': 1}
"""
vegaseat commented: very nice code +8