vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

It is ...

import time
# some of your code here ...
time.sleep(2)
# ... more code

... or you can use ...

from time import sleep

sleep(2)
HLA91 commented: Quick and helpfull +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a case where you don't know exactly how many arguments you will be passing to a Python function:

# explore the argument tuple designated by *args
# used for cases where you don't know the number of arguments
def sum_average(*args):
    size = len(args)
    sum = 0
    for k in args:
        sum += k
    # return a tuple of three arguments
    return args, sum, sum/float(size)


print sum_average(2, 5, 6, 7)  # ((2, 5, 6, 7), 20, 5.0)

# or unpack into a tuple of appropriate variables
tuple, sum, average = sum_average(2, 5, 6, 7)

print "sum of %s = %d" % (tuple, sum)  # sum of (2, 5, 6, 7) = 20

print "average of %s = %0.2f" % (tuple, average)  # average of (2, 5, 6, 7) = 5.00

# or just pick one return value, here value at index 1 = the sum
print "sum =", sum_average(2, 5, 6, 7)[1]  # sum = 20
Mouche commented: always really helpful with python +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Are you trying to printf() a double into an integer format specifier %d?
You could cast to an integer, but it looks like you are flirting with the integer size limits.

Line commented: Thanks for the help! ;o) +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

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

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

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You are declaring functions residential_rate(), commercial_rate(), industrial_rate() also as floats of the same name in function main(). Remove those variables and it will work!

Oops, I was too slow! Sorry Mister Dragon near St Louis!

Grunt commented: Helps-[Grunt] +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Try something like:

int counter = 1 ;
while (counter <= 4 )
{
   printf ("Enter the weight %d: ", counter) ;
   scanf ("%d", &my_weight [counter - 1] ) ;
   
   if ( some_condition_of_validity)
   {
      counter ++ ;
    }
   else
   {
      printf ("Incorrect choice!!!") ;
    }
}

This should keep on asking the user the choice until he enters a correct number.

One mild problem from past experience, if the users enters a floating point number, this loop spins out of control. Give it a try, it's good exercise.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a small project, go through all the functions listed at:
http://www.phim.unibe.ch/comp_doc/c_manual/C/FUNCTIONS/funcref.htm
and come up with a code sample of a practical application for each function.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am a little confused, hope this will help ...

# create a row of colorful buttons and assign some action to each
from Tkinter import *

def action1():
    label1.config(text='You pressed button1')
    
def action2():
    label1.config(text='You pressed button2')
    
def rng():
    label1.config(text='Now you could be running an RNG!')

form1 = Tk()
form1.title('Press a button')

# assign desired function object to command of each button
button1 = Button(form1, text='button1', fg='blue', command=action1)
button2 = Button(form1, text='button2', fg='brown', command=action2)
rng_button = Button(form1, text='run RNG', bg='green', command=rng)
quit_button = Button(form1, text='<< quit >>', fg='red', command=form1.destroy)
label1 = Label(form1, fg='red', bg='yellow')

# use a grid to place widgets on the form
button1.grid(row=0, column=0)
button2.grid(row=0, column=1)
rng_button.grid(row=0, column=2)
quit_button.grid(row=0, column=3)
label1.grid(row=1, column=0, columnspan=4)

form1.mainloop()
reRanger commented: Always very helpful and concise. +1
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

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

Here is an example of the classical "Guess a Number" game:

# guess a number game ...

import random

x = random.randint(1,100)

total = 0
while True:
    guess = int(raw_input("Guess a number between 1 and 100: "))
    total += 1
    if guess == x:
        print "Correct in %d guesses!" % (total)
        break
    elif guess < x:
        print "Too low!"
    else:
        print "Too high!"

Now improve the game, by telling the user not only "low" or "high", but also how close by selecting from a list like ["very hot", "hot", "warm", "cold", "very cold"].

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

# are the items in a list unique:
def is_list_unique(list1):
    """are the items in list1 unique, returns True or False"""
    return len(list1) == len(set(list1))
 
list1 = [1, 2, 3, 4, 5]
print is_list_unique(list1)  # True
 
list2 = [1, 2, 3, 3, 4, 5]
print is_list_unique(list2)  # False
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A simple guess the word game. This Python program takes a word and shuffles the characters, asking you to guess the original word. You could pick a word at random from a list of words and make a nice game.

import random

str1 = "Mississippi"
# convert to a list of char
charList = list(str1)
# shuffle the char
random.shuffle(charList)
# convert back to a word
str2 = "".join(charList)
# and show it ...
print "Guess this word --> %s" % (str2)
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This little code shows 6 random integer numbers from 1 to 50 ...

import random

print "show 6 random integers from 1 to 50:"
for k in range(6):
  r = random.randint(1, 50)
  print r,
print

Rewrite the code to make sure there are no duplicate numbers amongst the six numbers displayed.

Now let the user enter six unique numbers from 1 to 50 and then count how many tries it takes the computer to match 3, 4, 5 or 6 of the user's numbers, using the above random number example. You might recognize this as a way to figure out the chances to win a lotto game.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Construct a keyboard using a GUI like Tkinter that allows you to type by clicking on the displayed keyboard keys.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Use Python code to write a digital stopwatch program.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

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

[list2.append(item) for item in list1 if
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

To get happy it's Southern Comfort straight up!

To quench the thirst it's red California table wine like a decent Cabernet Sauvignon with about 1/3 orange juice all ice cold!

When gambling I like to keep my wits and drink hot chocolate.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The following little Python code will bring up your default webbrowser and connect it to the given URL ...

import webbrowser
 
# you have to be connected to the internet
# supply a URL of your choice
webbrowser.open('http://www.python.org/')

You can write a Python program that picks a URL from a list of fun URLs at random and be surprised what comes up.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Write a program that goes through a given directory and writes a log file containing all the filenames, modification times and filesizes. Then on a later date, the program will check this log file to detect any changes in the directory of modification dates, file sizes, new files and deleted files. It will let the user know of any changes.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Simply drawing a number of geometric lines, curves or shapes on a canvas can create a fairly good looking piece of art. Of course, your art teacher might disagree, but you are a better judge anyway!

You can size, locate and color your drawing objects at random, or in a predetermined progression using a mathematical formula driven by a loop or recursive function. It's amazing what comes out of those experimentations.

Take a look at the fractal tree snippet at:
http://www.daniweb.com/code/snippet510.html

Some colorful random drawings:
http://www.daniweb.com/code/snippet384.html

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The code below shows a simple Tkinter GUI calculation template, that has two labeled input fields, a button to trigger the calculation and a label to show the result ...

# example of two labeled entries, button and result label
# uses grid to position widgets also sets focus/cursor
# a rather generic Tkinter GUI template for calculations
 
from Tkinter import *
 
def calculate():
    try:
        # get the enter1 and enter2 values
        num1 = float(enter1.get())
        num2 = float(enter2.get())
        # do the calculation
        result = num1 * num2
        # display the result string
        label3.config(text=str(result))
    except ValueError:
        label3.config(text='Enter numeric values!')
 
root = Tk()
#root.config(bg='yellow')
 
# first entry with label
label1 = Label(root, text='Enter a number:')
label1.grid(row=0, column=0)
enter1 = Entry(root, bg='yellow')
enter1.grid(row=1, column=0)
 
# second entry with label
label2 = Label(root, text='Enter another number:')
label2.grid(row=2, column=0)
enter2 = Entry(root, bg='yellow')
enter2.grid(row=3, column=0)
 
# do the calculation by clicking the button
btn1 = Button(root, text='Multiply Numbers', command=calculate)
btn1.grid(row=4, column=0)
 
# display the result in this label
label3 = Label(root)
label3.grid(row=5, column=0)
 
# start cursor in enter1
enter1.focus()
# value has been entered in enter1 now switch focus to enter2
enter1.bind('<Return>', func=lambda e:enter2.focus_set())
 
root.mainloop()

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

You can use this template with slight modifications to do all sorts of scientific and financial calculations. You can also add more labeled Entry widgets to create a GUI based mortgage calculator. Dream up something useful or playful!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Since hexadecimal numbers are really strings representing a numeric value, you best convert these strings to a denary (base 10) number, do the mathematical operation and change the result back to the hexadecimal. Here is an example ...

def add_hex2(hex1, hex2):
    """add two hexadecimal string values and return as such"""
    return hex(int(hex1, 16) + int(hex2, 16))

print add_hex2('0xff', '0xff')  # 0x1fe
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

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

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

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

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

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

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Someone should write a palindrome program for every computer language there is. Python knows how to handle strings and makes it relatively easy ...

# check if a phrase is a palindrome
 
def isPalindrome(phrase):
    """
    take a phrase and convert to all lowercase letters
    if it matches the reverse spelling then it is a palindrome
    """
    phrase_letters = [c for c in phrase.lower() if c.isalpha()]
    print phrase_letters # test
    return (phrase_letters == phrase_letters[::-1])
 
 
#phrase = "A man, a plan, a canal, Panama!"
phrase = "Madam in Eden I'm Adam"
if isPalindrome(phrase):
    print '"%s" is a palindrome' % phrase
else:
    print '"%s" is not a palindrome' % phrase
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

An example how to run a number of different games or utilities from a menu. The menu is within an infinite while loop with a quit option to break out of the loop. The games or utilities are implemented with a function call ...

import random
import time
import calendar
 
def guess_number():
    # random integer 1 to 99
    n = random.randint(1, 99)
    #print n # test
 
    while True:
        print
        guess = int(raw_input("Enter an integer from 1 to 99: "))
        if guess < n:
            print "guess is low"
        elif guess > n:
            print "guess is high"
        else:
            print "you guessed it!"
        print
        break
 
def calendar_now():
    """show the calendar for the present month"""
    year_month = time.localtime()[:2]
    print
    calendar.prmonth(year_month[0], year_month[1])
    print
 
while True:
    print "-" * 30
    print " Menu"
    print "to guess a number enter n"
    print "for a monthly calendar enter m"
    # more ...
    print "to quit enter q"
    print "-" * 30
    # also convert any upper case choice to lower case
    choice = raw_input("enter your choice: ").lower()
    if choice == 'n':
        guess_number()
    elif choice == 'm':
        calendar_now()
    # more elif here ...
    elif choice == 'q':
        print
        print "thanks for using my program!"
        break
    else:
        print "enter the correct choice!"
    print
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

There are quite a number of songs out there with fairly repetitive lyrics. The "99 bottles of beer on the wall" song is an example, or this cute little example of a lyrics writer for the "old McDonald had a farm" song:

# print the lyrics of the song "Old McDonald had a farm"
# using functions to reduce your work
 
def print_exclamation():
    print 'Ee ai ee ai oh!'
 
def print_refrain():
    print 'Old McDonald had a farm.'
    print_exclamation()
 
def print_song(animal, sound):
    print_refrain()
    print 'And on his farm he had a ' + animal + '.'
    print_exclamation()
    print 'With a ' + 2 * (sound + ' ') + 'here,'
    print 'And a ' + 2 * (sound + ' ') + 'there.'
    print 'Here a ' + sound + ', there a ' + sound + '.'
    print 'Everywhere a ' + sound + ' ' + sound + '.'
    print_refrain()
 
print_song('cow', 'moo') # test it with the cow that sounds moo

Sit down with the kids and see what other songs you could pythonize!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Probably the simplest way to get into multimedia with Python is the webbrowser module. This works with both Windows and Unix systems, and selects the default browser you have installed. But that is not all: if you give it the name of a multimedia file it will select the default viewer or player, at least in Windows systems.

An example sound file might look like this:

import webbrowser
# opens .wav file with default wave sound player
webbrowser.open("Train.wav")

Whereas to display a bitmap graphics file you would have something like:

import webbrowser
# opens a .bmp file with default picture viewer
webbrowser.open("Train.bmp")

But the real power of the webbrowser module can be seen when you realize that it will load the browser with HTML code that can quickly be created from within a Python script. What this gives you is the ability to combine a picture with some sound, as highlighted in the following example:

import webbrowser
# html code to show a picture with sound effect
# you can replace files train.bmp and train.wav in the code
# with an image (.bmp, .gif, .jpg) and sound file (.wav, .au) you have
# you may need to change width and height to fit your own picture
# make sure the image and sound files are in the working folder
str1 = """
<html>
<head>
<title>Bring up an image with sound</title>
</head>
<body>

<img src = "train.bmp" width=320 height=210 border=5>

<bgsound src = "train.wav" loop=2>

</body>
</html>
Ene Uran commented: sweet +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Hyper Text Markup Language (HTML) is the backbone of a typical web page. Here is a very simple example:

<HTML>
<HEAD>
<TITLE>Link Lesson 1: Link Text</TITLE>
</HEAD>
<BODY>
The <A HREF="http://www.google.com">The Google Site</A> can be used to search
a large number of things, including  your favorite edible rhizome.
</BODY>
</HTML>

Write a Python function that extracts the url "http://www.google.com" from the HTML code. In other words, extract a substring from a text that is between two given substrings, here "=" and ">".

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

A small project, but practical. Let's say you have a string of all the abbreviated months of the year:

str1 = "JanFebMarAprMayJunJulAugSepOctNovDec"

How can you extract the abbreviated month from that string given the number of the month (eg. 8 = "Aug")?

A later thought, how could you convert the above string to a list like ...

['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

In other words, split the string at the capital letters.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Take a list of words like:

list1 = ['Herring', 'used', 'to', 'be', 'abundant', 'in', 'the', 'Atlantic', 'Ocean', 'then', 'herring', 'got', 'overfished']

and sort the list to show something like:

['Atlantic', 'Herring', 'Ocean', 'abundant', ... ]

Now sort the list case insensitive, so it looks more like:

['abundant', 'Atlantic', 'be', 'got', ... ]

Reverse this sorted list.

Sort the list by the lenght of the word, shortest word first.

Make the words in the list unique, note that Herring and herring are considered the same word.

Just a Python brain teaser, have fun!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Some people are indubitably spooked by a Friday falling on the 13th of the month. Write a program to list all the Friday the 13th of a given year.

(Hint: look at modules datetime and calendar)

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Write a biorhythm program in Python. You have to input the birthday and present day, and then calculate the physical, emotional and intellectual values.

For more details on biorhythms see:
http://en.wikipedia.org/wiki/Biorhythm

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Some of the answers are contained in the thread called "Starting Python" just above this thread.

If you run your program from the IDE editor than you should see the result in the output window. In Windows, if you double click on the saved .py file, then python.exe gets invoked and the result shows up in the old white on black cmd window. To see the result, you have to add a line to the end of your program that makes cmd wait for a key stroke. Something like that:

print "Hello truculent World!"

raw_input("Press any key ...")   # wait for key stroke

Python has to be installed on any computer you want to run your code on! One way around this requirement is to package your program with a free program called Py2Exe that creates an .exe file that includes the needed modules and the interpreter. That's more for people that want to distribute commercial programs.

The Python shell has a >>> prompt and is only used to test short code samples. It is ugly and confusing at best, I only use it for things like help("os"). If you run Python.exe you get the >>> shell in the old sinister cmd window, disgusting! Use an IDE editor to write, save and run your programs! IDEs like IDLE invoke Pythonw.exe, and pipe the result to their own more pleasant output window.

Have fun with Python, it is an easy to read and very powerful computer language!

EriCartman13 commented: thanks for the help +2
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

So you want to add an image to your Tkinter GUI program, here is an example ...

from Tkinter import *
 
root = Tk()
 
# reads only GIF and PGM/PPM images
# for additional formats use Image, ImageTk from PIL
# pick a GIF file you have in your working directory
imagefile = "Flowers.gif"
photo1 = PhotoImage(file=imagefile)
 
width1 = photo1.width()
height1 = photo1.height()
canvas1 = Canvas(width=width1, height=height1)
canvas1.create_image(width1/2.0, height1/2.0, image=photo1)
canvas1.pack()
root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I am thinking about a "snappy comeback" program. You enter a question and the program analyses the question for certain verbs or nouns and tries to come up with an answer. Could be silly or fun!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Looking around the internet, I haven't found a nice hangman game yet written in Python. You can use a simple ASCII character graphics or go fancy with a GUI drawing canvas (Tkinter or PyGame). Might even be able to use a chopped up image and hang your less favorite politician or used car dealer.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

You can create a list by concatination and multiplication. The example below shows you a practical approach ...

# in English you print first as 1st, second as 2nd and so on
# create a list of suffixes for the days of the month (1 to 31)
# rather than typing 17 'th' for numbers 4 to 20 you can use 17*['th']
 
day_suffix = ['st', 'nd', 'rd'] + 17*['th'] + ['st', 'nd', 'rd'] + 7*['th'] + ['st']
print day_suffix
"""
result =
['st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'th',
'th', 'th', 'th', 'th', 'th', 'st', 'nd', 'rd', 'th', 'th', 'th', 'th', 'th', 'th', 'th', 'st']
"""
 
# now test it
for x in range(1, 32):
    print "%d%s" % (x, day_suffix[x-1])
 
"""
result =
1st
2nd
3rd
4th
5th
...
30th
31st
"""
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This little code effort came out of one of the forum questions. The function calendar.prmonth(2006, 3) prints a neat little monthly calendar, can the output be assigned to a string for other uses? Here is one way to do this ...

# pipe the output of calendar.prmonth() to a string
 
import subprocess
 
code_str = \
"""
import calendar
calendar.prmonth(2006, 3)
"""
 
# save the code
filename = "mar2006.py"
fout = open(filename, "w")
fout.write(code_str)
fout.close()
 
# execute the code and pipe the result to a string
test = "python " + filename
process = subprocess.Popen(test, shell=True, stdout=subprocess.PIPE)
process.wait()
print process.returncode # 0 = success, optional check
# read the result to a string
month_str = process.stdout.read()
 
print month_str

There are simpler methods, but this is a good example of the os.popen() function, or the more updated subprocess.Popen().

Just remember to stick with a proportional font like Courier to line things up correctly.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just an example how to work with Tkinter's color pick dialog ...

# select a color and color the root window
 
from Tkinter import *
import tkColorChooser
 
#help('tkColorChooser')
 
root = Tk()
 
colorTuple = tkColorChooser.askcolor()
 
print colorTuple # for red = ((255, 0, 0), '#ff0000')
print colorTuple[1] # #ff0000
 
root.configure(bg=colorTuple[1])
 
root.mainloop()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Here is a class that allows you to convert Fahrenheit to Celcius or the reverse.

# class to convert F to C or C to F
# getFahrenheit(self) would be public
# __getFahrenheit(self) is private
# (double underline prefix makes method private to class)

class Temperature (object):
    """allows you to convert Fahrenheit to Celsius and vice versa"""
    def __init__(self):
        self.celsius = 0.0
    def __getFahrenheit(self):
        return 32 + (1.8 * self.celsius)
    def __setFahrenheit(self, f):
        self.celsius = (f - 32) / 1.8
    # property() combines get and set methods into one call
    fahrenheit = property(fget = __getFahrenheit, fset = __setFahrenheit)

d = Temperature()

# setting celsius value ==> getting fahrenheit value
d.celsius = 25
print "%0.1f C = %0.1f F" % (d.celsius, d.fahrenheit)

# setting fahrenheit value and getting celsius value
d.fahrenheit = 98
print "%0.1f F = %0.1f C" % (d.fahrenheit, d.celsius)

You might need to add a few test prints to figure that one out.
Note that there is a double unterline (aka dunter) before and after init.

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Let's assume you are working for the NSA and wanted to use Python to profile large amounts of e-mail that you are intercepting.

Write three fictitious e-mails, one a business e-mail, one a love/romance e-mail and one e-mail from Ladun Bing Osman to an accomplice that threatens your country.

Now use Python's text handling prowess to profile the three letters, so the dastardly letter can be identified. Check if fragments of words can do this.

Note: As of this time there are over 10 billion (yes, billion!) e-mails each day worldwide. Would be tough to read them all in person! To this you can add about 15 billion spam e-mails!

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Two small examples of sorting in Python. The first example shows you how to sort a list of numeric strings as strings or as integers. The results are quite different ...

# sort a list of numeric strings:
 
list1 = ['0', '100', '28', '39', '1', '1003']
 
print "Original list of numeric strings:"
print list1
 
print "Sort as strings:"
list1.sort()
print list1 # ['0', '1', '100', '1003', '28', '39']
 
print "Sort as integers (Python24):"
list1.sort(key=int)
print list1 # ['0', '1', '28', '39', '100', '1003']

The second examples shows you how to sort two related lists in parallel, so the relationships stay intact ...

# sort two lists in parallel ...
# create two lists of same length
list1 = ['one', 'two', 'three', 'four']
list2 = ['uno', 'dos', 'tres', 'cuatro']
 
# create a list of tuples, (english, spanish) pairs
data = zip(list1, list2)
print data # [('one', 'uno'), ('two', 'dos'), ('three', 'tres'), ('four', 'cuatro')]
 
# can use parallel looping to display result ...
for english, spanish in data:
    print english, spanish # one uno etc.
 
# each whole tuple will be sorted
data.sort()
print data # [('four', 'cuatro'), ('one', 'uno'), ('three', 'tres'), ('two', 'dos')]
 
# if you need two lists again after sorting then use ...
list3, list4 = map(lambda t: list(t), zip(*data))
print list3 # ['four', 'one', 'three', 'two']
print list4 # ['cuatro', 'uno', 'tres', 'dos']
 
# if you need just two tuples use ...
tuple1, tuple2 = zip(*data)
print tuple1 # ('four', 'one', 'three', 'two')
print tuple2 # …
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Just a little thing about reverse spelling I picked up from the internet ...

# reverse the spelling of an input string
# string reverse slice [::-1] introduced in Python23
# reversed() introduced in Python24
 
text = raw_input("Enter a string: ")
print text[::-1]
 
# or
print raw_input("Enter a string: ")[::-1]
 
# or
print ''.join(reversed(raw_input("Enter a string: ")))
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Some neat code from the forum. The question was:
... when I take a list with duplicates and make it a set then the duplicates are gone. How can I find out which were those duplicates?

A good solution came from monkeyy ...

lst1 = list('a list of characterstrings')
for item in set(lst1):
    print item, 'counted', lst1.count(item), 'times'
 
"""
result =
a counted 3 times
  counted 3 times  (space)
c counted 2 times
e counted 1 times
...
"""

Edit: changed l to lst1

vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This shows you how to start an external file from within Python code. In this case a small Windows media player to play midi or MP3 files. Sorry, the funky graphics display only gets active with .mp3 files. A zip file with the player and a few sample midi files is attached.

# play a midi file with an external midiplayer like
# the small (32k) BCX created WMPlay5.exe by vegaseat
 
import subprocess
import os
 
midi_player = "WMPlay5.exe"
# change folder and midi file to your needs
midi_folder = "D:/Python24/Atest/Mplay"
midi_file = "DGZ1.mid"
 
player = os.path.join(midi_folder, midi_player)
midi = os.path.join(midi_folder, midi_file)
 
subprocess.call([player, midi])
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

This is an example of a word frequency program. It combines a few lines to make it look shorter, but I hope you can still figure it out ...

str1 = """Man who run in front of car, get tired.
Man who run behind car, get exhausted."""
 
# create a list of lower case words
word_list = str1.lower().split(None)
 
# create a word:frequency dictionary
word_freq = {}
for word in word_list:
    # strip any trailing punctuation marks
    if word[-1:] in ".,!?;:":
        word = word.rstrip(word[-1:])
    word_freq[word] = word_freq.get(word, 0) + 1
 
# create a sorted list of keys
keys = sorted(word_freq.keys())
for word in keys:
    print "%-10s %d" % (word, word_freq[word])
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

The beauty of the PMIDI module is that you can produce sound, be it music or soundeffects, within your program with a few lines of code. This way you don't have to load a number of wave files (.wav) that are typically between 5k and 250k in size. Here is an example ...

# some sound effects using PMIDI
# NewNote(beat,duration,note,octave)

from PMIDI import *
from time import sleep

def bird():
    seq = Sequencer()
    song = seq.NewSong()
    voice = song.NewVoice(0)
    voice.SetInstrumentByName('Bird Tweet')
    m = voice.NewMeasure()
    m.NewNote(0, 8, 'A', 5)
    m.NewNote(8, 8, 'D', 5)
    m.NewNote(16, 8, 'A', 5)
    seq.Play()
    sleep(1.2)   # enough seconds to play
    seq.Close()

def gun():
    seq = Sequencer()
    song = seq.NewSong()
    voice = song.NewVoice()
    voice.SetInstrumentByName('Gunshot')
    m = voice.NewMeasure()
    m.NewNote(0, 12, 'F', 4)
    seq.Play()
    sleep(0.8)   # enough seconds to play
    seq.Close()

def wood():
    seq = Sequencer()
    song = seq.NewSong()
    voice = song.NewVoice()
    voice.SetInstrumentByName('Woodblock')
    m = voice.NewMeasure()
    m.NewNote(0, 24, 'G', 3)
    seq.Play()
    sleep(1)   # enough seconds to play
    seq.Close()


bird()    # bird chirps
sleep(1)  # wait a second
gun()     # idiot shoots it
sleep(1)
wood()    # bird hits ground
Osleff commented: Very helpful! +0
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

I used to program in C/C++ and still scan the forums. It is amazing how many people write functions within a function either by design or mistake caused by poor identation.

In contrast to C/C++ Python does allow you to define functions within a function, but remember that they are local to that function, unless you apply special considerations. Let's take a look ...

# define functions within a function
 
def printCircle(radius):
    """functions defined within this function are strictly local"""
    def pi():
        # pi is built in, but this is for the demonstration
        return 355/113.0
    def circleArea(r):
        return pi()*r*r
    def circleCircumference(r):
       return pi()*2*r
    # access the local (nested) functions
    print "A circle with a radius of %f ..." % radius
    print "... has an area of %f" % circleArea(radius)
    print "... has a circumference of %f" % circleCircumference(radius)
 
printCircle(1)
 
#print pi()  # local, would give NameError: name 'pi' is not defined
 
print
 
def func1 () :
    """a function can return local functions"""
    def func2 () :
        print "this is a message from func2"
    def func3 () :
        print "this message courtesy of func3"
    # needed to access the local functions globally
    return func2, func3
 
#func2()  # would give NameError: name 'func2' is not defined
 
# let Python know that func2 and func3 are in func1
func2, func3 = func1()
# now you can call these functions
func2()
func3()
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

If you have a list of tuples, you can sort by the index of the tuple element, as long as the tuples have the same number of elements. In some cases the first element of each tuple can be used as a sorting key. Here is an example showing the different alternatives at your disposal.

# sorting a list of tuples by tuple index
 
def sortTupList(myList, n):
    """sort a list of tuples by tuple index n, returns a new list"""
    nlist = [(x[n], x) for x in myList]
    nlist.sort()
    return [val for (key, val) in nlist]
 
def sortTupList_inplace(myList, n):
    """sort a list of tuples by tuple index n in-place, myList will change"""
    myList[:] = [(x[n], x) for x in myList]
    myList.sort()
    myList[:] = [val for (key, val) in myList]
 
 
originalList = [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]
 
# make a copy of the original list, beginning to end
newList1 = originalList[:]
# basic sort in-place, only sorts by first element (index=0) in tuple, list will change
# (first element may be used as a sorting key)
newList1.sort()
 
print newList1   # [(1, 'cat', 'small'), (2, 'ape', 'medium'), (3, 'bull', 'large')]
 
# make a copy of the original list, beginning to end
newList2 = originalList[:]
# sort in-place, sorts by specified element (index=2) in tuple, list will change
sortTupList_inplace(newList2, 2)
 
print newList2   # [(3, 'bull', 'large'), (2, 'ape', 'medium'), (1, 'cat', 'small')]
 
# sort by specified element (index=1) of the tuple, original list will not change
newList3 =
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

Take a look at:
http://www.daniweb.com/code/snippet395.html

This Python code snippet shows you how to replace multiple words in a text with matches in a dictionary. You could create a dictionary of slang words and make interesting texts.