Python's lambda allows you to declare a one-line nameless minifunction on the fly. The format is:
lambda parameter(s): expression using the parameter(s)
It returns the result of the expression. The expression has to be a one-liner (no newlines)! Here is a little example ...

# a list of player (name, score) tuples
player_score = [('frank', 88), ('jerry', 68), ('albert', 99)]

# use lambda to sort by score
# (the item at index 1 in the tuple)
player_score.sort(key=lambda tup: tup[1], reverse=True)

print(player_score)  # [('albert', 99), ('frank', 88), ('jerry', 68)]
Lardmeister commented: good example +10

List comprehension is something Python borrowed from a language called Haskell. It returns a new list and is shorter and simply faster than the traditional loop/append alternative. Look at the two functions and you can get an idea how list comprehension works within the one-line [ ... ].

# the module profile is used to compare the two functions
 
import profile
 
def evenList1():
    """returns a list of even numbers from 0 to 99998 using append in a loop
    the 50000 calls to append() consume a lot of CPU time
    """
    L1 = []
    for x in range(100000):
        if x % 2 == 0:
            L1.append(x)
    return L1
 
def evenList2():
    """returns a list of even numbers from 0 to 99998 using list comprehension
    much faster in CPU time than the standard loop with append()
    """
    L2 = [ x for x in range(100000) if x % 2 == 0 ]
    return L2
 
 
# test first 30 elements
print( evenList1()[0:30] )
print( evenList2()[0:30] )
 
print
print( "Profile of evenList1(), check the time consumed by the many append() calls:" )
print( "(ignore time consumed by the profiler itself)\n" )
profile.run('evenList1()')
 
print( "Profile of evenList2():" )
print( "(ignore time consumed by the profiler itself)\n" )
profile.run('evenList2()')

Can you figure results?

a, b, c, d, e = range(100, 1000, 200)

print a, b, c, d, e

If you have been thinking about some GUI programming using wxPython, one hassle is to properly position and size the widgets (components) on the coordinates of the window. I prefer to use the position (x, y) tuple for the upper left corner of the widget, and the size (width, height) tuple. For example ...

# wx.Choice(parent, id, pos, size, choices, style)
 
import wx
 
class MyPanel(wx.Panel):
 
    def __init__(self, parent, id):
        # initial panel fills the frame
        # pos defaults to (0, 0) and size to (-1, -1)
        wx.Panel.__init__(self, parent, id)
        self.SetBackgroundColour("white")
 
        # assigning keys-words, style is not used and  assumes a default style
        self.choice1 = wx.Choice(self, -1, pos=wx.Point(10, 10), size=wx.Size(100, 150), choices=tenList)
        # a little less typing ...
        #self.choice1 = wx.Choice(self, -1, pos=(10, 10), size=(100, 150), choices=tenList)
        self.Bind(wx.EVT_CHOICE, self.selChoice1, self.choice1)
 
        # simpler, but you have to follow the exact parameter sequence
        # (parent, id, position_tuple, size_tuple, choices)
        self.choice2 = wx.Choice(self, -1, (170, 10), (100, 150), oneList)
        self.Bind(wx.EVT_CHOICE, self.selChoice2, self.choice2)
 
    def selChoice1(self, event):
        item1 = event.GetString()
        print "choice1 =", item1   # test
 
    def selChoice2(self, event):
        item2 = event.GetString()
        print "choice2 =", item2   # test
 
 
oneList = ['one', 'two', 'three', 'four']
tenList = ['ten', 'twenty', 'thirty', 'forty']
 
 
app = wx.PySimpleApp()
# create a window/frame, no parent, -1 is default ID, title, size
# pos is not used and defaults to (0, 0)
frame = wx.Frame(None, -1, "wx.Size", size = (400, 310))
MyPanel(frame,-1)
frame.Show(True)
app.MainLoop()

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 = sortTupList(originalList, 1)
 
print newList3   # [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]
 
# similar to above, but using operator.itemgetter() and sorted() (needs Python24)
import operator
index1 = operator.itemgetter(1)
newList4 = sorted(originalList, key=index1)
 
print newList4   # [(2, 'ape', 'medium'), (3, 'bull', 'large'), (1, 'cat', 'small')]

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()

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])

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])

A logic shortcut:

x, y, z = 1, 2, 3
# test if y value is between x and z value
if x < y < z:
    print x, y, z  # 1 2 3
print
# same test, longer logic
if x < y and y < z:
    print x, y, z  # 1 2 3
print

Notice you can even do logic tests like:

if u < w < v < y < x:
    do some things

hey i am interested in programming, and i dont know where to start. i found this forum on google. can anyone please help.

Edited by vegaseat: Start right here!!!! If you have any questions, please start a thread in the regular Python forum!

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

The thread regarding 'how to do input in python' is great ..
Thanks for the contribution

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: ")))

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 # ('cuatro', 'uno', 'tres', 'dos')

This littel program allows you to find which key had been pressed using the Tkinter GUI.

# bind and show a key event with Tkinter 

from Tkinter import *

root = Tk()
prompt = '      Press any key      '
label1 = Label(root, text=prompt, width=len(prompt))
label1.pack()

def key(event):
    if event.char == event.keysym:
        msg = 'Normal Key %r' % event.char
    elif len(event.char) == 1:
        msg = 'Punctuation Key %r (%r)' % (event.keysym, event.char)
    else:
        msg = 'Special Key %r' % event.keysym
    label1.config(text=msg)

label1.bind_all('<Key>', key)

root.mainloop()

This code shows how to input a series of integers each separated by a space and then convert that input to a list of those integers:

# input a sequence of integer numbers separated by a space and convert to a list

def get_integer_list():
    while True:
        # get the sequence string and strip off any trailing space (easy mistake)
        str1 = raw_input("Enter a sequence of integers separated by a space: ").rstrip()
        try:
            # create a list of integers from the string using list comprehension
            return [int(num) for num in str1.split(" ")]
        except ValueError:
            print "Error: '%s' is not an integer! Try again." % num
            
print get_integer_list()

For example the input 1 2 3 4 5 turns into [1, 2, 3, 4, 5]

This small code allow you to list your computer's environment, things like processor, os, user and so on:

# list the environmental settings of your computer

import os

keys = os.environ.keys()
keys.sort()
for item in keys:
    print "%-22s : %s" % (item, os.environ[item])

As a bonus another small code to find the IP address of your computer:

# Get the IP address of the machine this program is running on
# or go to http://www.whatismyip.com/

import socket

print socket.gethostname()
print socket.getaddrinfo(socket.gethostname(), None)
# get just the IP address from the list's tuple
print socket.getaddrinfo(socket.gethostname(), None)[0][4][0]

Networks using the TCP/IP protocol route messages based on the IP address of the destination. An IP address is a 32-bit numeric address written as four numbers separated by periods.

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.

This was part of a game, I modified slightly the code. The code checks that input is correct and within a supplied range.

def checkInput(type_string, present_value, low, high):
    '''uses a while loop, loops until an acceptible answer is given, then returns it'''
    prompt = "Present %s is %d, enter a new value (%d-%d): " % (type_string, present_value, low, high)
    while True: 
       try:
          a = int(raw_input(prompt))
          if low <= a <= high:
             return a
       except ValueError:
          print "Enter an integer number, please!"


# modify the present strength of 10 within the range (1-18)
modified_strength = checkInput("strength", 10, 1, 18)
print modified_strength

Code sample shows how to run a program and specified file(s) from commandline.

# using commandline to run a program and files

def process_datafile(filename):
    """load specified data file and process data"""
    # code to read file data
    # code to process data and show or return result
    print "Test only, file =", filename   # testing

if __name__ == '__main__':
    import sys

    # run the progam from the commandline and specify the data file(s) to be loaded
    # something like   myProgram data1.dat data2.dat
    if len(sys.argv) > 1:
        # sys.argv is a list eg. ['C:/Python24/Atest/myProgram.py', 'data1.dat', 'data2.dat']
        # sys.argv[0] is program filename, slice it off with sys.argv[1:]
        # using for loop, more than one datafile can be processed
        for filename in sys.argv[1:]:
            process_datafile(filename)
    else:
        print "usage myProgram datafile1 [datafile2 ...]"

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()

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.

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
"""

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()

You can use a global variable within a function by prefixing it with the word "global". Here is an example:

# keep track of how many times a function has been accessed
# using a global variable, somewhat frowned upon
def counter1():
    global count
    # your regular code here
    count += 1
    return count

# test it
count = 0         # a global variable
print counter1()  # 1
print counter1()  # 2
print count       # 2  variable count has changed
print

The trouble with a global variable is with using it somewhere else in a large program. Everytime you call this function its value will change and may lead to buggy code.

One solution is to use the namespace of the function, making the variable more unique. It gives you a hint where it is used, for example:

# avoid the global variable and use the function namespace
def counter2():
    # your regular code here
    counter2.count += 1
    return counter2.count    

# test it
counter2.count = 0  # now count has counter2 namespace, notice the period
print counter2()    # 1
print counter2()    # 2
print

Ever wrote a Python program and wanted to use passwords? What good is password, if the user can simply look at your code and see it?

The module md5 comes to the rescue! It converts the password string to string containing series of hexadecimal numbers. You do that in program1, then copy and paste this hex string into your program (program2).

Here is program1 (keep that to yourself in save place):

# program 1, code to generate a hashed password
# the result is a series of hexadecimal numbers
# it is saved to one text file, so you can
# copy and paste it to program2 from any editor

import md5

# pick a password you can remember
password = "gummy"
pw_hashed = md5.md5(password).hexdigest()
print pw_hashed  # just testing
fout = open("MyHashedPassword.txt", "w")
fout.write(pw_hashed)
fout.close()

This is program2, showing only hex string hashed password, but user has to enter password 'gummy' for md5 to match:

# program2, copy hashed password from program1 and assign
# it to MYPASSWORDHASH as string, this is all user would see,
# if looking at your code

import md5

MYPASSWORDHASH = "c1944508a0d871c55b501624c36e0f68"
def get_password():
    # give it three tries
    for i in range(3):
        password = md5.md5(raw_input("Enter your password: "))
        password = password.hexdigest()
        if password == MYPASSWORDHASH:
            return True
    return False

def main():
    if get_password():
        print "Success"
        # do something here with rest of the program code
    else:
        print "Failure"
        # do something else here

if __name__ == "__main__":
    main()

Python allows you to combine a number of statements into one-liner:

str1 = "we willing women want warm winter woollies"

list1 = str1.split()
print list1  # ['we', 'willing', 'women', 'want', 'warm', 'winter', 'woollies']

list2 = [frag[:2] for frag in list1]
print list2  # ['we', 'wi', 'wo', 'wa', 'wa', 'wi', 'wo']

str2 = "".join(list2)
print str2  # wewiwowawawiwo

# combine all three statements
print "".join([frag[:2] for frag in str1.split()])

Here you have it, but watch out it becomes hard to read and understand at times. Me thinks, me just invented a new word "wewiwowawawiwo". Has nifty ring to it!

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

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

You can use Python program to extract picture from web page and save it. I have tested this with Windows XP, might work with other OS:

# load given picture from web page and save it
# (you have to be on the internet to do this)

import urllib2
import webbrowser
import os

# find yourself a picture on a web page you like
# (right click on the picture, look under properties and copy the address)
picture_page = "http://www.google.com/intl/en/images/logo.gif"

#webbrowser.open(picture_page)  # test

# open the web page picture and read it into variable
opener1 = urllib2.build_opener()
page1 = opener1.open(picture_page)
my_picture = page1.read()

# open file for binary write and save picture
# picture_page[-4:] extracts extension eg. .gif
# (most image file extensions have three letters, otherwise modify)
filename = "my_image" + picture_page[-4:]
print filename  # test
fout = open(filename, "wb") 
fout.write(my_picture)
fout.close()

# was it saved correctly?
# test it out ...
webbrowser.open(filename)
Be a part of the DaniWeb community

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