vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The odds are eight to ten that the light at the end of the tunnel is the headlight of an oncoming train.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

As you get older, you realize that life is full of freeloaders. Luckily, some of us feel good about working, to have a sense of accomplishment etc.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a couple of Rodney Dangerfield's famous lines:

I drink too much. The last time I gave a urine sample it had an olive in it.

I found there was only one way to look thin, hang out with fat people.

I get no respect. The way my luck is running, if I was a politician I would be honest.

I had plenty of pimples as a kid. One day I fell asleep in the library. When I woke up, a blind man was reading my face.

I have good looking kids. Thank goodness my wife cheats on me.

I haven't spoken to my wife in years. I didn't want to interrupt her.

I looked up my family tree and found three dogs using it.

I met the surgeon general - he offered me a cigarette.

I remember the time I was kidnapped and they sent a piece of my finger to my father. He said he wanted more proof.

I told my dentist my teeth are going yellow. He told me to wear a brown tie.

I told my psychiatrist that everyone hates me. He said I was being ridiculous - everyone hasn't met me yet.

My psychiatrist told me I was crazy and I said I want a second opinion. He said okay, you're ugly too.

I told my wife the truth. I told her I was seeing a psychiatrist. Then she told me the …

thekashyap commented: nice one.. :) +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

So who wants flies?

A fly fisher person perhaps, or someone who puts flies into ointments.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You are in luck, I just went food shopping:
12 large eggs $2
gallon of milk $4
loaf of whole wheat bread $2
4 boneless pork chops $5
1 pound of cheddar cheese $6
1 pound of cottage cheese $3
1 pound of butter $3
a jar of peaches $2 (actually comes from SA)

Sulley's Boo commented: :D cute +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An ugly carpet lasts forever.

Did you know that with every passing hour, our solar system comes forty-three thousand
miles closer to globular cluster 13 in the constellation Hercules?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The Democrats are farther left.

My old aunt is so afraid of lefties, that she only makes right turns in traffic.

Ancient Dragon commented: :) +21
Aia commented: We need to learn from people that have lived longer. +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The strange title comes from a skit by Benny Hill, where he tells his wife all the facts she shouldn't know, but she always answers "I know! I know!"

Anyway, this thread is suppose to be a collection of strange facts. Let's have fun!

Here are a few facts to ponter:

A duck's quack doesn't echo, and no one knows why.

Hershey's Kisses are called that because the machine that makes them looks like it's kissing the conveyor belt.

The name Jeep came from the abbreviation used in the army for the "General Purpose" vehicle or G.P.

The mask used by Michael Myers in the original "Halloween" was actually a Captain Kirk mask painted white.

GrimJack commented: Really great thread - but may be time to close this one and start anew +7
codeorder commented: quite interesting and almost as good as a cup of coffee.:) +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Write a Python program that converts the string 'supercalifragilisticexpialidocious' to the string 'SuPeRcAlIfRaGiLiStIcExPiAlIdOcIoUs'.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

So did Stalin...
Obama like Clinton is a leftist extremist. Obama on top of that is a fundamentalist Muslim.

Vote for him if you want Sharia law in the US, vote for Clinton if you want the US to turn into North Korea.

For heaven sake jwenting, you are losing it. Please see professional help.

jbennet commented: agree +23
Ezzaral commented: Definitely +4
iamthwee commented: I disagree, Jwenting is an articulate right wing extremist. Pay hommage to him. -2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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):
        """allow for additional (derived) attributes"""
        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 …
Ene Uran commented: neat +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is an example using the common Tkinter GUI toolkit ...

# Tkinter, show the button that has been clicked

import Tkinter as tk

def click(event):
    s = "clicked: " + event.widget.cget("text")
    root.title(s)

root = tk.Tk()
root.geometry("300x50+30+30")

b1 = tk.Button(root, text="button1")
b1.bind("<Button-1>", click)
b1.pack()

b2 = tk.Button(root, text="button2")
b2.bind("<Button-1>", click)
b2.pack()

root.mainloop()
Racoon200 commented: Good knowledge +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
# %r uses repr() and %s uses str()
# for example ...
print "%r tag requires exactly two arguments" % "this"
print "%s tag requires exactly two arguments" % "this"
"""
my output -->
'this' tag requires exactly two arguments
this tag requires exactly two arguments
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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
ball_radius = 0.7
ball = vs.sphere(pos=(-5, 0, 0), radius=ball_radius, color=vs.color.red)
# 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
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Maybe, when they cut the throats of the goats, some sacrificial blood spattered onto the plane's loose wiring and made it hold its contact. No, it was most likely the god of flight and fertility.

Neat title for the thread Salem!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just to interject the lighter side of the nuptials into this sometimes sober discussion ...

By all Means... MARRY!
I recently read that love is entirely a matter of chemistry.
That must be why my wife treats me like toxic waste.
- David Bissonette

When a man steals your wife, there is no better revenge than to let him keep her.
- Sacha Guitry

After marriage, husband and wife become two sides of a coin; they just can't face each other, but still they stay together.
- Hemant Joshi

By all means marry. If you get a good wife, you'll be happy.
If you get a bad one, you'll become a philosopher.
- Socrates

Woman inspires us to great things, and prevents us from achieving them.
- Dumas

The great question... which I have not been able to answer... is, 'What does a woman want?
- Sigmund Freud

I had some words with my wife, and she had some paragraphs with me.
- Anonymous

'Some people ask the secret of our long marriage. We take time to go to a restaurant two times a week. A little candlelight, dinner, soft music and dancing.
She goes Tuesdays, I go Fridays.'
- Henny Youngman

'I don't worry about terrorism. I was married for two years.'
- Sam Kinison

'There's a way of transferring funds that is even faster than electronic banking.
It's called marriage.'
- James Holt …

Sulley's Boo commented: =D +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

My boss is the sweetest person, may she stay on vacation forever!

iamthwee commented: Nice interpretation! +11
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Write an anagram program that takes someone's name and uses all the letters to create a phrase, for instance:
Osama Bin Laden --> 'bad neon salami'
George W Bush --> 'whose bugger'
George Bush --> 'he bugs Gore'
Tony Blair --> 'bony trail'
Ronald Reagan --> 'loan arranged'
David Letterman --> 'nerd amid late TV'
Elvis --> 'lives'

... beyond names:
The Morse Code --> Here Come Dots
Slot Machines --> Cash Lost in'em
Mother-in-law --> Woman Hitler
Statue of Liberty --> Built to Stay Free
New York Times --> Monkey writes
eleven plus two --> twelve plus one

You could also write a Python program that checks the above anagrams for correctness.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague
# the numbers in this list have the same sum and product
lst = [0.5, 1.2, 3.75, 4.36]
 
# test the assertion ...
print 0.5 * 1.2 * 3.75 * 4.36  # 9.81
print sum(lst)                 # 9.81

1) Test this assertion using a for loop.
2) Can you come up with other such lists, using Python to help you?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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:

Download and install boa-constructor-0.6.1.bin.setup.exe from:
http://sourceforge.net/project/downloading.php?group_id=1909&use_mirror=osdn&filename=boa-constructor-0.6.1.bin.setup.exe&74856058

Then run Boa.exe

1) Start with 'File'/'New'/'wx.Frame'
(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 …

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Nice deduction there kath! Python does equate True with 1 and False with 0.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Not better, but cute, create your own display window with a Windows message box ...

// use a message box to display console output
// compile as GUI
#include <windows.h>
#include <string.h>
#include <stdlib.h>
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
  char output[1000];
  char st[20];
  int number, sum;
  
  for ( number = 2; number <= 1000; number += 2 )
    sum += number;
  // convert int to string
  // Pelles C uses _itoa() instead of itoa()
  _itoa(sum, st, 10);
  // build up output string
  strcpy(output, "The sum of even integers from 2 to 1000 is ");
  strcat(output, st);
  
  // now send the result to a Windows message box
  MessageBox(NULL, output, "Show console output in a MessageBox", MB_OK);
  return 0;
}
Aia commented: Thank you +5
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In Python these kind of things are a lot easier than in C#. Here is a typical example ...

sentence = 'the dog barks'
 
# create a list of words (default=whitespaces)
words = sentence.split()
 
# take a look
print words  # ['the', 'dog', 'barks']
 
# now reverse the list of words
rev_words = reversed(words)
 
# join the reversed list to a sentence again (' '=space)
rev_sentence = ' '.join(rev_words)
 
# look at rev_sentence
print rev_sentence  # barks dog the
 
# you can do that all on one line
print ' '.join(reversed(sentence.split()))
Matt Tacular commented: What would we beginner python programmers do without you? +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Interesting indeed!
Us humble human beings can readily observe matter and energy, but not the state between the two. Let's postulate that 'dark matter' is this flux state, observed only by its gravitational pull. If you believe this, you sleep better at night. It has the soothing effect of a good sermon, those always put me to sleep too!

Aia commented: Awesome. +4
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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 …

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Crypting text is always fun, here is a simple rotation crypt (enough to make the NSA guys laugh) ...

# simple rotation crypting of lowercase strings
 
import string
 
shift_right_by2 = string.maketrans(string.ascii_lowercase,
    string.ascii_lowercase[2:] + string.ascii_lowercase[:2])
 
# test --> cdefghijklmnopqrstuvwxyzab
print string.ascii_lowercase[2:] + string.ascii_lowercase[:2]
 
shift_left_by2 = string.maketrans(string.ascii_lowercase,
    string.ascii_lowercase[-2:] + string.ascii_lowercase[:-2])
 
# test --> yzabcdefghijklmnopqrstuvwx
print string.ascii_lowercase[-2:] + string.ascii_lowercase[:-2]
 
print "hello world".translate(shift_right_by2)  # jgnnq yqtnf
print "jgnnq yqtnf".translate(shift_left_by2)   # hello world
 
# stay below 26 or you go full circle
# --> abcdefghijklmnopqrstuvwxyz
print string.ascii_lowercase[26:] + string.ascii_lowercase[:26]

You can try other shift values from 1 to 25. If you use 26, you go once around the circle of course. How would you include capital letters?

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In the restroom at work, the Boss had placed a sign
directly above the sink. It had a single word on it
-- "Think!"

The next day, when he went to the restroom, he looked
at the sign and right below, immediately above the soap
dispenser, someone had carefully lettered another sign
which read -- "Thoap!"

William Hemsworth commented: Great one :) +3
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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,
Ene Uran commented: great find +13
tushg commented: Hi Vegaseat :) Nice One :) could you please help me my Python Pyraimid is NOT WORKING :( Pls http://www.daniweb.com/software-development/python/threads/438405/running-the-project-application-in-pyramid-python-is-not-working# +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Python is not for everbody! If you are an entrenched traditional language (C, C++, Java, C#, Pascal) person, Python, because of its elegance, will be too confusing for you.

iamthwee commented: Good point +9
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a windows machine, you can achieve accuracy better than 1 millisecond with time.clock() ...

# time.clock() gives wallclock seconds accurate to at least 1 millisecond
# it updates every millisecond, but only works with windows
# time.time() is more portable, but has quantization errors
# since it only updates updates 18.2 times per second
 
import time
 
print "\nTiming a 1 million loop 'for loop' ..."
start = time.clock()
for x in range(1000000):
  y = 100*x - 99  # do something
end = time.clock()
print "Time elapsed = ", end - start, "seconds"
 
"""
result -->
Timing a 1 million loop 'for loop' ...
Time elapsed =  0.471708415107 seconds
"""

The module timeit has accuracy better then 1 microsecond and turns off garbage collection too. However, it is mostly used to time statements and functions.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

In a GUI print and input are replaced by label and entry components. Here is a typical example ...

# a simple Tkinter number guessing game
 
from Tkinter import *
import random
 
def click():
    # get the number in the entry area
    num = int(enter1.get())
    # check it out
    if num > rn:
        label3['text'] = 'Guessed too high!  Enter another number!'
    elif num < rn:
        label3['text'] = 'Guessed too low!  Enter another number!'
    else:
        label3['text'] = 'Guessed correctly!'
    
# create the main/root window
root = Tk()
root.title()
 
# pick a random integer from 1 to 10
rn = random.randrange(1, 11)
 
# let the user know what is going on
label1 = Label(root, text="Guess a number between 1 and 10")
label1.grid(row=1, column=1, padx=8, pady=8)
 
# prompt the user
label2 = Label(root, text="Enter an integer number: ")
label2.grid(row=2, column=1, padx=20, pady=8)
 
# this your input area
enter1 = Entry(root, width=5)
enter1.grid(row=2, column=2, padx=8)
enter1.focus()
 
# this is your mouse action button, right-click it to execute command
button1 = Button(root, text=" Press to check number ", command=click)
button1.grid(row=3, column=1, pady=8)
 
# the result displays here
label3 = Label(root, text="", bg='yellow')
label3.grid(row=4, column=1, columnspan=2, pady=8)
 
# start the mouse/keyboard event loop
root.mainloop()
fredzik commented: A lifesaver, very helpful. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something like this will work ...

import Tkinter
def win1():
    # this is the main/root window
    root = Tkinter.Tk()
    root.title("Window 1")
    startButton = Tkinter.Button(root, text="Start", command=win2)
    startButton.grid(row=9, column=7)
    leaveButton = Tkinter.Button(root, text="Quit", command=root.destroy)
    leaveButton.grid(row=1, column=1, sticky='nw')
    b1Var = Tkinter.StringVar()
    b2Var = Tkinter.StringVar()
    
    b1Var.set('b1')
    b2Var.set('b2')
    box1Label = Tkinter.Label(root,textvariable=b1Var,width=12)
    box1Label.grid(row=3, column=2)
    box2Label = Tkinter.Label(root,textvariable=b2Var,width=12)
    box2Label.grid(row=3, column=3)
    root.mainloop()

def win2():
    # this is the child window
    board = Tkinter.Toplevel()
    board.title("Window 2")
    s1Var = Tkinter.StringVar()
    s2Var = Tkinter.StringVar()
    s1Var.set("s1")
    s2Var.set("s2")
    square1Label = Tkinter.Label(board,textvariable=s1Var)
    square1Label.grid(row=0, column=7)
    square2Label = Tkinter.Label(board,textvariable=s2Var)
    square2Label.grid(row=0, column=6)

win1()

Renamed 'top' so it less confusing.

NikkieDev commented: Dude you are amazing +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Seems to be too simple to be homework. You were almost there, you should only multply the overtime pay by 1.5.

"""
output should be:
Pay rate $10.00
Regular Hours 40
Overtime hours 20
Regular pay $400.00
Overtime pay $300.00
Total Pay $700.00
"""
def hours():
    hours = input("How many hours did you work?: ")
    return hours
 
def payrate():
    payrate = input("How much is the payrate?: ")
    return payrate
 
def calchours(pr, h):
    if h > 40:
        rh = 40
        oh = h - 40
    else:
        rh = h
        oh = 0
    print "Pay rate $%0.2f" %  pr
    print "Regular Hours %d" % rh
    print "Overtime hours %d" % oh
    print "Regular pay $%0.2f" % (rh * pr)
    print "Overtime pay $%0.2f" % (oh * pr * 1.5)
    print "Total Pay $%0.2f" % (rh * pr + oh * pr * 1.5)

def main():
    hrs = hours()
    pyr = payrate()
    calchours (pyr, hrs)
 
main()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Note that the images are objects not strings, so you have to do this ...

import Tkinter
import random
import Image, ImageTk
 
def changeImage():
    global listOfImages
    im = listOfImages[random.randint(0,8)]
    box1Label.configure(image=im)
    
top = Tkinter.Tk()
r7 = ImageTk.PhotoImage(file="gfx/r7.jpg")
b7 = ImageTk.PhotoImage(file="gfx/b7.jpg")
A = ImageTk.PhotoImage(file="gfx/A.jpg")
B = ImageTk.PhotoImage(file="gfx/B.jpg")
C = ImageTk.PhotoImage(file="gfx/C.jpg")
f = ImageTk.PhotoImage(file="gfx/f.jpg")
G = ImageTk.PhotoImage(file="gfx/G.jpg")
P = ImageTk.PhotoImage(file="gfx/P.jpg")
O = ImageTk.PhotoImage(file="gfx/O.jpg")
# images are objects not strings
listOfImages = [r7, A, C, B, b7, f, P, G, O]
 
box1Label = Tkinter.Label(top, image=r7)
box1Label.grid(row=3, column=2)
changeButton = Tkinter.Button(top, text="Change", command=changeImage)
changeButton.grid(row=9, column=7)
 
Tkinter.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Best to use a grid ...

# using Tkinter's grid() to place widgets
import Tkinter as tk
root = tk.Tk()
# create some buttons
button1 = tk.Button(root, text='button1')
button2 = tk.Button(root, text='button2')
button3 = tk.Button(root, text='button3')
# create a label for kicks
label1 = tk.Label(root, text="hello Matty!", fg='red', bg='yellow')
# use a grid to place the buttons
# stay in the same row and add columns
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
button3.grid(row=0, column=2)
# place the label in the next row
# span across 3 columns, pady (vertical), stretch label horizontally
label1.grid(row=1, column=0, columnspan=3, pady=5, sticky=tk.E+tk.W)
# run the event loop
root.mainloop()
mattyd commented: always helpful \ matty d +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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
image = pg.image.load(image_file).convert()
# 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 …

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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
# add some color
 
# 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 …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here are some projects that require a little library work and Google searching at first.

1) Write a simple Python code to C++ code converter
2) Write a small Python "Expert System"
3) Write a Python program the applies Artificial Intelligence (AI)
4) Write a Python "Data Mining" program

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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 ... …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Below is the Python code for a simple console blackjack game. It's just you against the computer ...

# a simple blackjack game to figure out the ace_1_11 algorithm
from random import choice as rc
def total(hand):
    # how many aces in the hand
    aces = hand.count(11)
    # to complicate things a little the ace can be 11 or 1
    if aces == 1:
        t = sum(hand)
        if t > 21:
            # evaluate the ace as a 1
            t = t - 10
    elif aces == 2:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
    elif aces == 3:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
                if t > 21:
                    # evaluate third ace as a 1
                    t = t - 10
    elif aces == 4:
        t = sum(hand)
        if t > 21:
            # evaluate one ace as a 1
            t = t - 10
            if t > 21:
                # evaluate second ace as a 1
                t = t - 10
                if t > 21:
                    # evaluate third ace as a 1
                    t = t - 10
                    if t > 21:
                        # evaluate fourth ace as a 1
                        t = t - 10
    # …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Something else you want to consider, the Python Image Library (PIL) has a Tkinter portion called ImageTk. I have had not much time to play with that.

mattyd commented: Always Helpful and Inspiring to Coders. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

# class Teacher and class Student inherit from class SchoolMember

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

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

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

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

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

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

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

print '-'*55

# list of instances, Teacher t1 and Students s1 ... s5
members = [t1, s1, s2, s3, s4, s5]
sumgrades = 0
for member in members:
    memberType = member.detail()
    try:
        sumgrades += member.grades
    except AttributeError:
        pass # this …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This sample code should shed some light on class inheritance ...

# class Teacher and class Student inherit from class SchoolMember

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

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

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

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

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

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

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

print '-'*55

# list of instances, Teacher t1 and Students s1 ... s5
members = [t1, s1, s2, s3, s4, s5]
sumgrades = 0
for member in members:
    memberType = member.detail()
    try:
        sumgrades += member.grades
    except AttributeError:
        pass # this would be a teacher, has no grades so skip
    
print "\n%s's …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is one example that explains a little about self and class instance and method:

# a typical Python class example
# newer class convention uses inheritance place holder (object) 

class Account(object):
    # __init__() initializes a newly created class instance,
    # 'self' refers to the particular class instance
    # and also carries the data between the methods.
    # You have to supply the initial account balance 
    # during creation of the class instance.
    def __init__(self, initial):
        self.balance = initial

    def deposit(self, amt):
        # a function within a class is called a method
        # self always starts the argument list of a method
        self.balance = self.balance + amt

    def withdraw(self,amt):
        self.balance = self.balance - amt
        
    def getbalance(self):
        return self.balance 


# create two new class instance, Mary's and Tom's account
mary = Account(1000.00) # start with initial balance of 1000.00
tom = Account(3000.00)  # tom is lucky he starts with 3000.00

# Mary makes deposits and a withdrawel
mary.deposit(500.00)
mary.deposit(23.45)
mary.withdraw(78.20)

# Tom also accesses his account
tom.withdraw(1295.50)

# now look a the account balances
print "Mary's balance = $%0.2f" % mary.getbalance()  # $1445.25
print "Tom's balance  = $%0.2f" % tom.getbalance()   # $1704.50
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I corrected your code in a few places, added a few missing self. prefixes. If you use a widget in one of the class methods, then you have to prefix it with self.

import wx
import os

ID_MENU_NEW_WIZ = 101
ID_MENU_SAVE    = 102
ID_MENU_LOAD    = 103
ID_MENU_EXIT    = 104
ID_MENU_HELP    = 105
ID_MENU_ABOUT   = 106
ID_RADIO_FORWARDS   = 201
ID_RADIO_STATIONARY = 202
ID_RADIO_BACKWARDS  = 203
ID_SPEED_LABEL      = 204    # first time!!!!
ID_SPEED_SLIDER     = 301
#ID_SPEED_LABEL         = 401  # second time!!!!
ID_SPEED_JUDDER_BUTTON = 402
# 501-> Reserved for Bristle manual control checkboxes
# 601-> Reserved for Cylinder manual control checkboxes
ID_ACTION_BUTTON_GO   = 701
ID_ACTION_BUTTON_STOP = 702
Speed = 3
Cylinders = 2
Bristles  = 3
 
class Frame1(wx.Frame): 
    def __init__(self, parent, title):
        wx.Frame.__init__(self, parent, -1, title, pos=(150, 150))
        Icon = wx.Icon("icon3.ico", wx.BITMAP_TYPE_ICO)
        self.SetIcon(Icon)
        
### MENU ###
        
        # Create a menubar at the top of the frame
        MenuBar = wx.MenuBar()
        FileMenu = wx.Menu()
        HelpMenu = wx.Menu() 
        # Add items to the menu
        FileMenu.Append(ID_MENU_NEW_WIZ, "&New Tractor Wizard\tCtrl-N", "Start the New Tractor wizard")
        FileMenu.Append(ID_MENU_SAVE, "&Save\tCtrl-S", "Save the current tractor configuration to file")
        FileMenu.Append(ID_MENU_LOAD, "&Load\tCtrl-L", "Open a tractor configuration from file")
        FileMenu.AppendSeparator()
        FileMenu.Append(ID_MENU_EXIT, "E&xit\tAlt-F4", "Exit the program")
        
        HelpMenu.Append(ID_MENU_HELP, "&Help\tF1", "Open the Help file")
        HelpMenu.AppendSeparator()
        HelpMenu.Append(ID_MENU_ABOUT, "&About", "About the program")
 
        # Bind the menu event to an event handler
        self.Bind(wx.EVT_MENU, self.OnMenuSave, id = ID_MENU_SAVE)
        self.Bind(wx.EVT_MENU, self.OnMenuLoad, id = ID_MENU_LOAD)
        self.Bind(wx.EVT_MENU, self.OnMenuExit, id = ID_MENU_EXIT)
        self.Bind(wx.EVT_MENU, self.OnMenuAbout, id = ID_MENU_ABOUT)

        # Put the menu on the menubar
        MenuBar.Append(FileMenu, "&File")
        MenuBar.Append(HelpMenu, "&Help")
        self.SetMenuBar(MenuBar)
        
 
### STATUS BAR ###
        
        self.CreateStatusBar()
 
### …
MarkWalker84 commented: Massively helpful! Thankyou! +1