The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!

The creators of Python are very active, improving the language all the time. Here is a little of the version history:
Python24 March 2005
Python25 Sept 2006
Python26 Sept 2008
Python27 July 2010 (final version of the Python2 series)
Python31 July2009
Python32 February 2011
Python33 September 2012
Python34 March 2014
You can download the version you like free from: www.python.org
As of 2014 stick with Python27 or Python34.
Selfextracting MS Installer files have a .msi extension and contain the version number, for instance python-3.4.1.msi.

Python3 is not totally campatible with Python2. A few clumsy things have been removed to modernize the language. One obvious one is the print statement, which is now a print() function and raw_input() has been changed to just input(). The old numeric input() is gone.

You can find an excellent discussion of Python2 to Python3 changes here:
(check appendix A for Py2-to-Py3 differences)

The good news is that Python3 contains a conversion program 2to3.py that will convert your present Python2 code to Python3 code.

Linux users can install Python installers from: http://www.activestate.com/activepython/python3/
For the folks who like to do the unusual, Python is equally at home on the Apple computers. It is my understanding that Linux and Apple OS X have Python already installed. Apple users should check http://undefined.org/python/

I installed my Python on the C: drive, so so version 3.4 I ended up with a C:\Python34 folder after the installation. The first step is to create a subfolder (subdirectory) for all your test programs, like C:\Python34\Atest34.

There is a Python editor included with the Python installation. The program is called IDLE, a small, but capable Integrated Development Environment (IDE), that you can use to write, edit, run and debug your code from. The problem is that it is hidden in subfolders. I found it in

The .py or .pyw extension is used for Python code files. With Windows, all you need to do is to double click on idle.pyw and after a fraction of a second the compiled program appears on your screen.

If your version of IDLE starts up in the Shell Window, the one with the >>> prompts, go to 'Options' on the top line and then click on 'Configure IDLE'. In the configure menu go to the 'General' page and set the 'Open Edit Window' at startup option, then click on 'Apply'.

Seniors see also: https://www.daniweb.com/software-development/python/threads/492345/old-old-programmer-needs-some-personal-help#post2153685

I think that coding in the interactive shell, also called the command line option, is limited to one liners, simple calculations and calls for help. Anything else is just major confusion, and has turned off a lot of fine folks from using Python! Lamentably, much of the Python docs are littered with command line examples with its many >>> prompts and ... line indent markers. Do not use those >>> prompts and markers in your code editor.

Once you are in the Edit Window with its simple flashing cursor, type in your first Python program (no, the line number is not part of the code).

print( "Hello Monty Python!" )

On the top menu bar click on File and save the short program in the Atest folder as HelloMP1.py now press the F5 key (or click on Run then on Run Module). The Python interactive Shell appears telling what version of Python you are running, and wedged between >>> prompts is Hello Monty Python!

Not much, but it worked, your first Python program. After you admired this for a while, press the Alt and F4 keys at the same time (or File then Close) to leave the Shell and get back to the Editor.

Let's create a second version of the simple program. Replace 'print' with 'str1 =' and add a few more lines ...

str1 = "Hello Monty Python!"
# this is a comment
# notice you don't have to declare the variable type
print( str1 )

If you want to, you can save this under a different filename, then press F5. The result looks the same, but we introduced a string variable and the fact that Python does not require us to declare the type. Oh gee! My C brain is going nuts!

One more change for the fun of it ...

str1 = "Hello Monty Python!"
# let's replace the M with Spam
str2 = str1.replace('M', 'Spam')
# one more Spam for the P
str3 = str2.replace('P', 'Spam')
# now look at the result
print( str1 )
print( str2 )
print( str3 )

Notice, as you type 'str1.replace(' a hint line pops up showing you what can be entered between the function's parentheses, a cool thing. When you are done typing the code, press F5 and enjoy your labor. I leave it to you to dream up better stuff! Also notice, that in all of this the original string str1 has not changed.

Want more? When you are in the IDLE editor simply press the F1 key and a copy of the Python documentation comes up. There you can click on Tutorial and now you have a ton of sample code to play with. Just cut and paste and experiment.

If you are in the Python interactive Shell, the one with the >>> prompt, you can just type help('string') to get a list of string functions and constants. A little cryptic at first, but still useful. In the Shell you can also do calculator stuff and get the result. For instance type 12345679 * 63 then press enter. By the way, you can also get into a somewhat uglier looking Shell when you simply run Python.exe from the Python31 folder.

For convenience sake make a shortcut of idle.pyw and drag it onto your desktop.

Just a note, I said earlier that with Python you don't have to declare the type of a variable. That is not totally true, you have to give Python an idea what it is. By inference Python figures out that if you type z = 77 then z is the reference to an integer object. Conversely z = "Hello" would be a string, z = 7.12 is a floating point number, and z = [] is a list (in this case an empty list ready to be populated).

You can find some Python tutorials at:

For GUI programming there are third party modules available:
Tkinter usually comes with the Python installation
wxPython and project Phoenix at http://www.wxpython.org/download.php
PyQT at http://www.riverbankcomputing.com
PySide at http://qt-project.org/wiki/PySide
I recommend PySide.

The Python Image Library (PIL, now pillow) is at:

The PyGame module for game programming is at:

Also look at this site for other Python third party modules:
(mostly binary Windows installers, now wheels)

A detailed and interesting essay about Python's creation and architecture:
Another good introduction into the design philosophy of Python:

Google offers a great Starting Python Class online:

Nice humor ...

A Foolish Consistency is the Hobgoblin of Little Minds ...
for recommended Python code writing style see:

Editor's note:
I have started to update some of the posts to reflect changes in Python3. Also changed some of the code to make it work with Python2 and Python3 versions. This is work in progress, tough for my old tired eyes. You will see the somewhat odd print( text ) rather than the recommended print(text), just a visual aid for me that I changed this from Python2. Remember in Python readability rules!

In order to visualize the execution of your Python code line by line use

For those of you who are used to the Microsoft Visual Studio there is a free Python option, check out:
A great website with a lot of hand holding advice.

On my iPad I use an IDE app called "Pythonista" that does a nice job with Python 2.7 (also has PIL, numpy, matplotlib, and a UI-editor). The app costs just a few bucks in the apple app store. See also:

Edited by vegaseat: sticky

Votes + Comments
Python, here I come! Thanks vegaseat.
how to declare dictinary
life saver!
Thanks! Great collection for Python. I've learned lots from your posts.
Great Intro to Python, for pretty long I have delayed getting my hands dirty with Python, after reading this I finally went in.
Awesome!Am starting Python myself!
great introduction to python!
11 Years
Discussion Span
Last Post by vegaseat
Featured Replies
  • 10

    For beginners in Python, this shows you how to define a function. Notice the format (parameters are often called arguments): [code=python] def function_name(arg1, arg2, ...): statement block return arg3, arg4, ... [/code] The statement lines that are part of the function have to be indented, since Python does not have … Read More

  • 4

    Python has a very helpful feature called help(). Here is a sample ... [code=python] # list all the modules Python currently knows about ... help("modules") # now pick a module from that list you want to know # more about ... # to get help about module calendar ... help("calendar") … Read More

  • 6

    One more helpful hint to get this thing off to a hopefully good start. How do we read a simple text file in Python? Also, what can we do with the data after we read it? [code=python] # read a text file to a string and create a list of … Read More

  • 4

    Since we are on the subject of modules that come with Python, there is the operating system module called simply os. Here is one thing you can use it for ... [code=python]# list all the configuration (.ini) files in C:\Windows import os fileList = [] # start with an empty … Read More

  • 5

    Questions about threading come up many times on the forum, so here some help ... [code]# running a function in the background with threading # apply threading to a function with a function decorator # without the threading decorator the function counter2 # would tick off first, then the other … Read More


Again, please do not clutter this thread with questions and homework problems!

The idea of this thread is to help the beginning Python programmer with hints and helpful code. Please feel free to contribute! If you have any questions start your own thread!


For beginners in Python, this shows you how to define a function. Notice the format (parameters are often called arguments):

def function_name(arg1, arg2, ...):
    statement block
    return arg3, arg4, ...

The statement lines that are part of the function have to be indented, since Python does not have a begin/end or {} pair for such things. The size of the indentation is a matter of preference. To me 2 spaces are more readable, the more or less official standard is 4 spaces. One word of advice, don't mix spaces and tabs for indentations! I avoid tabs.

In general, if a statement line ends with a colon (like a function define, a class, a for or while loop, or an if, elif, else), you have to indent the statement block that belongs to this line.

You must define a function before you call it. It is good practice to comment the function. It is also good practice to prefix a function with an action verb like format, get, convert, set etc. Here is an example of a number of functions receiving and passing arguments and working together in the classical data in, data process and data out fashion ....

def get_name():
    """this function only returns arguments"""
    first = "Fred"
    last = "Ferkel"
    return first, last

def show_name(name):
    """this function only receives an argument"""
    print( name )

def process_name(first, last):
    """this function reveives 2 arguments, returns 1 argument"""
    name = "Mr. " + first +" " + last
    return name

def main():
    this function handles the other functions in order
    and deals with the arguments received and to be passed
    first, last = get_name()
    name = process_name(first, last)

# start the program with this function call

"""my output -->
Mr. Fred Ferkel

The Python interpreter compiles all the defined functions to byte code, but does not use them until called. To avoid any problems, follow the simple rule of defining all functions in the beginning of your program ...

def f1():
    # call function f2

def f2():

def f3():

# all function have been defined
# this will work fine

Here a call is made before define ...

def f1():
    # call function f2

# oops, premature call, this will give
# NameError: global name 'f2' is not defined

def f2():

def f3():

Many Pythonians prefer this style of commenting functions ...

def formatDollar(amount):
    a function to format to $ currency
    (this allows for multiline comments)
    return "$%.2f" % amount
print( formatDollar(123.9 * 0.07) )
print( formatDollar(19) )

There is another use for the triple quoted comment or documentation string. You can access it like this ...

# accessing the documentation string
# (these are double underlines around doc)
print( formatDollar.__doc__ )

A more complete example ...

import math
def getDistance(x1, y1, x2, y2):
    getDistance(x1, y1, x2, y2)
    returns distance between two points using the pythagorean theorem
    the function parameters are the coordinates of the two points
    dx = x2 - x1
    dy = y2 - y1
    return math.sqrt(dx**2 + dy**2)
print( "Distance between point(1,3) and point(4,7) is", getDistance(1,3,4,7) )
print( "Distance between point(1,3) and point(11,19) is", getDistance(1,3,11,19) )
print( '-'*50 )  # print 50 dashes, cosmetic
print( "The function's documentation string:" )
# shows comment between the triple quotes
print( getDistance.__doc__ )

Actually, if your documentation string is just a one-liner, you could enclose it in just single quotes on the same line. If you don't like the indentation to show up in the documentation string, Python relaxes the indentation rules within a multiline string, so you can use use something like this:

def getDistance(x1, y1, x2, y2):
getDistance(x1, y1, x2, y2)
returns distance between two points using the pythagorean theorem
the function parameters are the coordinates of the two points
    dx = x2 - x1
    dy = y2 - y1
    return math.sqrt(dx**2 + dy**2)

Just a note on function or variable names, avoid using Python language keywords or Python's builtin function names. For a list of Python's builtin functions (also called methods) you can use this little code:

builtin_fuction_list = dir(__builtins__)
print( builtin_fuction_list )
print( "-"*70 )  # print a decorative line of 70 dashes
# or each function on a line using a for loop
for funk in builtin_fuction_list:
    print( funk )
print( "-"*70 )
# or each function on a line joining the list to a string
print( '\n'.join(builtin_fuction_list) )
print( "-"*70 )
# or, a little more advanced, combine it all and do a case insensitive sort too
print( '\n'.join(sorted(dir(__builtins__), key = str.lower)) )

Sorry, couldn't resist showing off the different ways to present the data.

To get a list of Python keywords use:

from keyword import kwlist
print( kwlist )

One more note, don't use names of variables you are using in your program for function names. They will compete within the Python interpreter internal dictionary and may lead to errors!

Since the correct indentations are so critical in Python code, it is best to use an editor written for Python. Those editors will auto-indent properly, warn you of mixed tab/space indentations and do some other hand holding. I have experimented with IDLE, PythonWin, DrPython, pyPE, and BOA constructor. They all have certain features I like. If you fiddle, I mean experiment with the code a lot, DrPython or PyPE comes in the handiest. BOA constructor makes GUI programming with wxPython much easier!

For a listing of Integrated Development Environment (IDE) programs for Python see:

Also not strictly an IDE, this is a very nice editor (written in Python/wxPython) with great features (multiple windows, syntax highlighting, find/replace, line numbers, autocomplete, macros, fold/expand functions and classes, bookmarks, todo, Python Shell, run your code, hotkeys, spellcheck and much more). Simply extract the zip file into your Python folder. Execute the program by running 'pype.pyw'. You can run your code with 'Run current file' and it will display in a nice output window (similar to the IDLE shell)
(written for Windows, but also tested on Linux, latest version PyPE-2.8-src.zip 12/14/2006)

Another very nice IDE for Python is PyScripter (still beta). This one is written with Delphi and is a standalone executable file. You can download the free setup file (for Windows only) from:

This free IDE is more general, but has a truckload full of real nice programmer's features:

Boa Constructor is an IDE with a visual frame builder/designer built in (like Delphi). It is still alive and kicking, and the latest version is nicely improved. Download the Windows version for free from:
Boa uses wxPython and works with Python2.5 or 2.6 and wxPython2.8 on Windows XP and Vista.

Edited by vegaseat: IDEs, Python3 update

Votes + Comments
great help

When you write a Python program like ...

# use slicing to spell a string in reverse 
str1 = "Winners never quit, quitters never win!"
# slicing uses [begin : end : step]
# end is exclusive
# defaults are begin = 0, end = len of string, step = 1
# use step = -1 to step from end 
print( "reverse = ", str1[::-1] )

... you can save it for instance as 'reverse.py' to a folder. If Python is installed on a Windows computer, you can simply double-click on the filename and run the program. The extension .py is usually associated with the Python interpreter.

Since this is a console program, you will run into the old troublemaker of the console output, the program runs but closes quickly. You have to add a line of code at the end of the program to make the console wait for some key input.

# use slicing to spell a string in reverse 
str1 = "Winners never quit, quitters never win!"
# slicing uses [begin : end : step]
# end is exclusive
# defaults are begin = 0, end = len of string, step = 1
# use step = -1 to step from end 
print( "reverse = ", str1[::-1] )
# optional wait for keypress
raw_input('Press Enter...')
# with Python3 'raw_input()' has become 'input()'

This is not needed, if you run from an IDE that has its own output window. BTW, if you are lost with the slicing thing str1[::-1] just fill in the defaults and it gets clearer
str1[0 : len(str1) : -1] .

Just a few more slicing examples ...

# slicing uses [start:<end:step]
s4 = "hippopotamus"
print( "first 2 char = ", s4[0:2] )
print( "next 2 char  = ", s4[2:4] )
print( "last 2 char  = ", s4[-2:] )
print( "exclude first 3 char  = ", s4[3: ] )
print( "exclude last 4 char   = ", s4[:-4] )
print( "reverse the string    = ", s4[::-1] )  # step is -1
print( "the whole word again  = ", s4 )
print( "spell skipping 2 char = ", s4[::2] )  # step is 2
my output -->
first 2 char =  hi
next 2 char  =  pp
last 2 char  =  us
exclude first 3 char  =  popotamus
exclude last 4 char   =  hippopot
reverse the string    =  sumatopoppih
the whole word again  =  hippopotamus
spell skipping 2 char =  hpooau

You can apply slicing to any indexed sequence, here is a list example ...

# exploring Python's slicing operator
# can be used with any indexed sequence like strings, lists, ...
# syntax --> seq[begin : end : step]
# step is optional
# defaults are index begin=0, index end=len(seq)-1, step=1
# -begin or -end --> count from the end backwards
# step = -1 reverses sequence
# if you feel lost, put in the defaults in your mind
# use a list as a test sequence
a = [0, 1, 2, 3, 4, 5, 6, 7, 8]

print( a[3:6] )   # [3,4,5]
# if either index is omitted, beginning or end of sequence is assumed 
print( a[:3] )    # [0,1,2]
print( a[5:] )    # [5,6,7,8]

# negative index is taken from the end of the sequence
print( a[2:-2] )  # [2,3,4,5,6]
print( a[-4:] )   # [5,6,7,8]

# extract every second element
print( a[::2] )   # [0, 2, 4, 6, 8]

# step=-1 will reverse the sequence
print( a[::-1] )  # [8, 7, 6, 5, 4, 3, 2, 1, 0]

# no indices just makes a copy (which is sometimes useful)
b = a[:]
print( b )    # [0, 1, 2, 3, 4, 5, 6, 7, 8]

# slice in (replace) an element at index 3
b[3:4] = [100]
print( b )    # [0, 1, 2, 100, 4, 5, 6, 7, 8]
# make another copy, since b has changed
b = a[:]

# slice in (insert) a few elements starting at index 3
b[3:] = [9, 9, 9, 9] + b[3:]
print( a )    # [0, 1, 2, 3, 4, 5, 6, 7, 8]
print( b )    # [0, 1, 2, 9, 9, 9, 9, 3, 4, 5, 6, 7, 8]

Edited by vegaseat: slicing examples


Python has a very helpful feature called help(). Here is a sample ...

# list all the modules Python currently knows about ...
# now pick a module from that list you want to know
# more about ...
# to get help about module calendar ...
# dito for the math module
# file stuff ...
# down to method/function level ...

That means you can use help in the program code, or at the interactive page >>> prompt. Not many other languages offer this handiness! To copy the help result into a help file see:

If you want other people to read and help with your code, you might want to follow the Python style guide, written by GVR himself:

Edited by vegaseat: code tags updated


One more helpful hint to get this thing off to a hopefully good start. How do we read a simple text file in Python? Also, what can we do with the data after we read it?

# read a text file to a string and create a list of words

# use any text file you have ...
textf = open('xmas.txt', 'r')
str1 = textf.read()

print( "The text file as one string:" )
print( str1 )

# splits at the usual whitespaces
wordlist = str1.split(None)
print( "\nThe string as a list of words:" )
print( wordlist )
print( "\nThere are %d words in the list." % len(wordlist) )

Want more help about split()? At the interactive page >>> prompt enter


One more function sample to show you that a function can decide internally what type of number to return. Also shows an example of try/except exception handling.

# a function to return the numeric content of a cost item
# for instance $12.99 or -$123456789.01 (deficit spenders)
def getVal(txt):
  if txt[0] == "$":    # remove leading dollar sign
    txt = txt[1:]
  if txt[1] == "$":    # could be -$xxx
    txt = txt[0] + txt[2:]
  while txt:           # select float or integer return
      f = float(txt)
      i = int(f)
      if f == i:
        return i
      return f
    except TypeError:  # removes possible trailing stuff  
        txt = txt[:-1]
  return 0
# test the function ...
print( getVal('-$123.45') )

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


The IDLE integrated development environment that comes with the normal Python installation is really a GUI program. It uses Tkinter as the GUI toolkit which is part of the normal Python installation. Tkinter uses tcl script language to do the work.

Here is a typical Python code example using Tkinter ...

# explore the Tkinter GUI toolkit

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

# create a window frame 
frame1 = tk.Tk() 
# create a label 
label1 = tk.Label(frame1, text="Hello, world!") 
# pack the label into the window frame
frame1.mainloop()  # run the event-loop/program

This code should run on Windows and Unix (PC or Mac). On a Windows machine save the program with a .pyw extension. This way it associates with pythonw.exe and avoids the ugly black DOS display popping up.

You can also find much Tkinter detail at:

There is another GUI library worth mentioning, it's wxPython based on C++. The code is more efficient for GUI stuff. The download of the installer is free, look at http://wiki.wxpython.org/

You can get wxPython for either Windows, Linux or Unix. You can find quite a few wxPython GUI code examples in the DaniWeb Python Code Snippets and in the Starting wxPython sticky. Here is a very nice wxPython tutorial I like to recommend, it will give you a good overview:

Note: GUI stands for Graphical User Interface. It's the usual Window matter like frames, buttons, labels, editboxes.

Edited by vegaseat: [code=python] tag


To get string input from the user you can use the raw_input() function with Python2 and the input() function with Python3. .

Here is an example of an input loop that checks the data you enter. The function get_list(prompt) is generic and can be used whenever you want to enter a series of numbers (accepts integer or float). It returns a list of the entered numbers. It's up to you to process the list of numbers ...

print( "The grade point average (GPA) calculator:" )
def get_list(prompt):
    loops until acceptable data or q (quit) is given
    returns a list of the entered data
    data_list = []
    while True:
        sin = raw_input(prompt)  # input(prompt) in Python3
        if sin == 'q':
            return data_list
            data = float(sin)
        except ValueError:
            print( "Enter numeric data!" )
gp_list = get_list("Enter grade point (q to quit): ")
print( gp_list )  # test
# process the list ... 
# calculate the average (sum of items divided by total items)
gpa = sum(gp_list)/len(gp_list)
print( "The grade point average is:", gpa )

Since Python2's raw_input() will not work with Python3, you can use try/except to make your program work with both versions ...

# use module datetime to show age in days
# modified to work with Python2 and Python3

import datetime as dt

prompt = "Enter your birthday (format = mm/dd/yyyy): "
    # Python2
    bd = raw_input(prompt)
except NameError:
    # Python3
    bd = input(prompt)

# split the bd string into month, day, year
month, day, year = bd.split("/")

# convert to format datetime.date(year, month, day))
birthday = dt.date(int(year), int(month), int(day))

# get todays date
today = dt.date.today()

# calculate age since birth
age = (today - birthday)

print( "You are %d days old!" % age.days )

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

A note on importing modules:
Python is a modular language and comes with many thoroughly tested and optimized modules. To code in Python means you have to use those modules to your advantage. Python syntax may be easy, but remembering all those modules may use all the power of your brain!

Edited by vegaseat: code=python tag remark, Python3 update


I need to write a function that can return more than one item. This is a simple example how to do it ...

# use a tuple to return multiple items from a function
# a tuple is a set of values separated by commas
def multiReturn():
    return 3.14, "frivolous lawsuits", "Good 'N' Plenty"
# show the returned tuple
# notice that it is enclosed in ()
print( multiReturn() )
# load to a tuple of variables
num, str1, str2 = multiReturn()
print( num )
print( str1 )
print( str2 )
# or pick just the element at index 1, should be same as str1
# tuples start at index zero just like lists etc.
print( multiReturn()[1] )

This example has not only a multiple argument return, but also allows you to call it with multiple arguments of flexible size/number ...

# 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)
    sum1 = sum(args)
    average = sum1/float(size)
    # return a tuple of three arguments
    # args is the tuple we passed to the function
    return args, sum1, average
# notice that the first element is the args tuple we send to the function
print( sum_average(2, 5, 6, 7) )  # ((2, 5, 6, 7), 20, 5.0)
# or unpack into a tuple of appropriate variables
args_tuple, sum2, average = sum_average(2, 5, 6, 7)
print( "sum of %s = %d" % (args_tuple, sum2) )  # sum of (2, 5, 6, 7) = 20
print( "average of %s = %0.2f" % (args_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

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


The Python module pickle allows you to save objects to file as a byte stream that contains the object information. When you load the file back the object is intact. Here is a little code example ...

# use binary file modes "wb" and "rb" to make pickle 
# work properly with both Python2 and Python3

import pickle
myList1 = [1, 2, 03, 04, 3.14, "Monty"]
print( "Original list:" )
print( myList1 )
# save the list object to file
file = open("list1.dat", "wb")
pickle.dump(myList1, file)
# load the file back into a list 
file = open("list1.dat", "rb")
myList2 = pickle.load(file)
# show that the list is still intact
print( "List after pickle.dump() and pickle.load():" )
print( myList2 )

The same procedure applies to other objects like variables, tuples, sets, dictionaries and so on.

Edited by vegaseat: [code=python] tag, Python3 update


The Python module calendar is another interesting collection of functions (methods). If you ever need to show all 12 monthly calendars for the year, use this code ...

# print out a given year's monthly calendars
import calendar

If you just want June 2005 use ...

import calendar
calendar.prmonth(2005, 6)
result -->
     June 2005
Mo Tu We Th Fr Sa Su
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

Just for fun, ask a C++ programmer to do this in two lines of code. Now you know why Python is considered a high level language.

Here is a somewhat more complete program, asking the user for the year ...

# allowing for user input
import calendar
print( "Show a given year's monthly calendars ..." )
# Python3 uses input() instead of raw_input()
year = int(raw_input("Enter the year (eg. 2005): "))
raw_input("Press Enter to go on ...")  # wait
# with Pytho3 use ...
#input("Press Enter to go on ...")  # wait

Note, print('') prints an empty line in Python2 and Python3.
Since I have Dev-C++ on my computer I tricked it into using Python and do the calendar thing.

// needs the Python-2.4.1.DevPak installed into Dev-C++, download from:
// http://prdownloads.sourceforge.net/devpaks/Python-2.4.1.DevPak?download
// create project with File > New > Project... > Scripting > Python
#include <iostream>
#include <string>
// run the Python interpreter eg. Python24.dll
// this macro saves on typing!
#define PY  PyRun_SimpleString(input.c_str())
using namespace std;
// include the Python library header
extern "C" {
  #include <python2.4/Python.h>
int main()
  // initialize Python
  // optional - display Python version information
  cout << "Python " << Py_GetVersion() << endl << endl << endl;
  string input;
  // this module is in Python24\lib as calendar.py
  // could include it in the working folder if problem
  input = "import calendar"; PY;
  // print out the year's monthly calendar
  input = "calendar.prcal(2005)"; PY;
  // finish up and close Python
  cin.get();  // console wait
  return 0;

Since we are on the subject of modules that come with Python, there is the operating system module called simply os. Here is one thing you can use it for ...

# list all the configuration (.ini) files in C:\Windows
import os
fileList = []  # start with an empty list
for filename in os.listdir("C:/Windows"):
    if filename.endswith(".ini"):
# now show the list
for filename in fileList:
    print( filename )

There are lots of things you can do with this module. I guess you just have to type help('os') in the interactive window (the one with the >>> prompt) .

You Mac folks will have to change the folder/directory name and the extension.


We have used the replace() function before. This time we use it in a for loop to create new words. The example also gives us a look at the if conditional statement ...

# make your own words, when Q comes up we want to use Qu
str1 = 'Aark'
print( "Replace A in %s with other letters:" % str1 )
# go from B to Z
for n in range(66, 91):
    ch = chr(n)
    if ch == 'Q':      # special case Q, use Qu
        ch = ch + 'u'
    print( str1.replace('A', ch) )

A variation of the above to show off the if/else statement ...

# make your own words, here we have to avoid one
# word to get past the guardians of the nation's morals
str1 = 'Auck'
print( "Replace A in %s with other letters:" % str1 )
# go from B to Z
for n in range(66, 91):
    ch = chr(n)
    if ch == 'Q':      # special case Q, use Qu
        ch = ch + 'u'
    if ch == 'F':      # skip the F word
        print( str1.replace('A', ch) )

These little code samples are fun to experiment with.

A note for the C programmers, Python treats characters as strings. This makes life a lot simpler!


Instead of reading a file, you can read the HTML code of a web site. Of course, you have to be connected to the internet to do this ...

# if you are on the internet you can access the HTML code of a given web site
# using the urlopen() method/function from the module urllib2
# tested with Python 2.5.4
import urllib2
urlStr = 'http://www.python.org/'
    fileHandle = urllib2.urlopen(urlStr)
    str1 = fileHandle.read()
    print '-'*50
    print 'HTML code of URL =', urlStr
    print '-'*50
except IOError:
    print 'Cannot open URL %s for reading' % urlStr
    str1 = 'error!'
print str1

Notice that we have added the try/except exception handling to this code.

Note: Python3 uses urllib.request.urlopen() instead of urllib2.urlopen()
If you use Python3, try this code ...

# get html code of given URL
# Python3 uses urllib.request.urlopen()
# instead of Python2's urllib.urlopen() or urllib2.urlopen()
# also urllib is a package in Python3 
# tested with Python 3.1

import urllib.request

fp = urllib.request.urlopen("http://www.python.org")
# Python3 does not read the html code as string
# but as html code bytearray
mybytes = fp.read()

# try utf8 to decode the bytearray to a string
mystr = mybytes.decode("utf8")

If you are the curious type and want to know beforehand whether you are connected to the internet, this code might tell you ...

# are we connected to the internet?
# tested with Python 2.5.4
import os
def isSSL():
    """ return true if there is a SSL (https) connection """
    if (os.environ.get('SSL_PROTOCOL', '') != ''):
        return true
        return false
if isSSL:
    print( "We have a SSL connection" )
    print( "No SSL connection" )

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


Do you want to impress your friends? Of course you do! Try this Python code example using the datetime module ...

# how many days old is this person?
from datetime import date
# a typical birthday  year, month, day
# or change it to your own birthday...
birthday = date(1983, 12, 31)
now = date.today()
print( '-'*30 )  # 30 dashes
print( "Today's date is", now.strftime("%d%b%Y") )
print( "Your birthday was on", birthday.strftime("%d%b%Y") )
# calculate your age
age = now - birthday
print( "You are", age.days, "days old" )

The datetime module is smart enough to catch erroneous dates like date(1983, 12, 32) or date(1983, 2, 29).

Notice the variation of the import statement. Here we are just importing the date method from the datetime module. This saves you from having to code:
now = datetime.date.today()
Might be good for long code where you would have to write this twenty times.

Here is another practical code ...

# calculate days till xmas
from datetime import date
now = date.today()
# you may need to change the year later
xmas = date(2005, 12, 25)
tillXmas = xmas - now
print( '-'*30 )  # 30 dashes
print( "There are", tillXmas.days, "shopping days till xmas!" )

Calculations like this can lead to a lot of headscratching, Python does it for you without a scratch ...

# add days to a given date
from datetime import date, timedelta
now = date.today()
delta = timedelta(days=77)
addDays = now + delta
print( '-'*30 )  # 30 dashes
print( "Today's date is   :", now.strftime("%d%b%Y") )
print( "77 days from today:", addDays.strftime("%d%b%Y") )

Impressed? I am!


This little fun with numbers program shows how range() and the for loop work together. A little trick I learned in fourth grade applied to Python.

# call it "all the same"
num1 = 12345679 # the 8 is left out!
# k goes from 9 to <82 in steps of 9
for k in range(9, 82, 9):
    print( num1 * k )

Here is another one ...

print("Bo Derek getting older:")
for k in range(10, 0, -1):

Edited by vegaseat: [code=python] tag


I took this from a recent thread, to show you how you can use a temporary print statement to figure out what is going on ...

# create a jumbled word/string
# tested with Python 2.5.4
import random 
# create a sequence, here a tuple, of words to choose from 
WORDS = ("python", "jumble", "easy", "difficult", "answer", "babysitter") 
# pick one word randomly from the sequence 
word = random.choice(WORDS) 
# create a variable to use later to see if the guess is correct 
correct = word 
# create a jumbled version of the word
# start with an empty string to be built up in the while loop
jumble = ""
# word is reduced in size by one character each time through the loop
# when it is empty it will be equal to None(False) and the loop stops
while word:
    print( word, '  ', jumble )   # for test only
    position = random.randrange(len(word)) 
    jumble += word[position] 
    word = word[:position] + word[(position + 1):]
print( jumble  )  # now you can ask to guess the word ...

Just a little note, when you save this code, don't save it as random.py. Python will confuse this in the import statement! It will look for the module random.py in the working directory first, before it goes the \Lib directory where the proper module is located.


Strings are immutable, which means you cannot directly change an existing string, bummer! The following code would give you an error ...

str1 = 'Hello World!'
str1[0] = "J"  # gives TypeError: object does not support item assignment

Where there is a will, there is a way around this obstacle ...

str1 = 'Hello World!'
# these statements give the intended result, since they create a new string
# slicing and concatination
str2 = 'J' + str1[1:]
# using replace()
str3 = str1.replace('H', 'J')
# or change the string to a list of characters, do the operation, and join the 
# changed list back to a string
charList = list(str1)
charList[0] = 'J'
str4 = "".join(charList)
print( str1 )
print( str2 )
print( str3 )
print( str4 )

Along the last thought, lets have some word fun ...

# just a little word fun ...
import random
str1 = "Mississippi"
charList = list(str1)
str2 = "".join(charList)
print( "\nString '%s' after random shuffle = '%s'" % (str1, str2) )

The last code example could be the start of a "guess the word" game.


Another recent thread was the impetus for this hint.

As you run the Python interpreter on a Python text code file (.py), the file is internally compiled to a .pyc byte code file that speeds up the interpretation process. Most of the time this is transparent to you, as the byte code file for speed sake is created in memory only.

If a Python text code .py file is imported by another Python file, a corresponding .pyc is created on disk to speed up the reuse of that particular file. Using .pyc files speeds things up saving the compilation step.

There is an additional benefit, the compiled files are not readable with a text editor. You can distribute your .pyc file instead of the .py file, this way you can hide your source code a little from folks who like to fiddle with source code.

Let's say you have a file called MyPyFile.py and want to create the compiled file MyPyFile.pyc for higher speed and/or the prevention of unauthorized changes. Write a little one line program like this:

import MyPyFile # converts MyPyFile.py to MyPyFile.pyc

Save it as CompileMyPyFile.py in the same folder as MyPyFile.py and run it. There now should be a MyPyFile.pyc file in that folder. Python.exe runs the source file or the compiled file.

Here is another way to create the compiled file ...

# create a byte code compiled python file
import py_compile
py_compile.compile("MyPyFile.py") # creates MyPyFile.pyc

Note: Changed code tags, looks like we lost the php tags!


Just simple code to construct a toggle button, in this case we are using the venerable Tkinter for the GUI implementation.

# make a toggle button with Tkinter
    # Python2
    import Tkinter as tk
except ImportError:
    # Python3
    import tkinter as tk
toggleFlag = True
def entryColor():
    """toggle the entry color between white and red"""
    global toggleFlag
    if toggleFlag:
        toggleFlag = False
        toggleFlag = True
# create the root window
root = tk.Tk()
# create a button, command runs the given function 
# when button is clicked
b1 = tk.Button(root, text="Toggle Color", command=entryColor)
# pack button into root window
b1.pack(fill=tk.BOTH, expand=1)
# create an entry box to color
e1 = tk.Entry(root)
e1.pack(fill=tk.BOTH, expand=1)
# start the event loop

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


A short code example of case sensitive and case insensitive string sorts ...

# sorting a list of strings

s = "I dearly love Monty Python's Flying Circus"
word_list = []
word_list = s.split()
print("The original list of words:")

# make a shallow copy since sort() is inplace
word_list1 = list(word_list)

print("\nSort this list (the default sort is case sensitive):")

word_list2 = list(word_list)
# use keword key to do a case insensitive sort
# applies lower() to every string item in the list during compare
print("\nHere is a sort that is case insensitive:")

"""my output -->
The original list of words:
['I', 'dearly', 'love', 'Monty', "Python's", 'Flying', 'Circus']

Sort this list (the default sort is case sensitive):
['Circus', 'Flying', 'I', 'Monty', "Python's", 'dearly', 'love']

Here is a sort that is case insensitive:
['Circus', 'dearly', 'Flying', 'I', 'love', 'Monty', "Python's"]

Edited by vegaseat: ref to snippets obsolete


In a recent thread we looked at ways to create a multiline string. Here are a few code samples showing you how to do this, some are preference, some are cosmetic ...

# a look at multiline strings
# using line continuation (\) to form one long/multiline string
# complex and tough to read
# (no space right after \ or an empty line following \)
str1 = "The alien gasps and says, 'Oh, this is it.  I will die! \n\
Tell my 2.4 million larvae that I loved them... \n\
Good-bye, cruel universe.' "
# using line continuation (\) to combine three strings to one string
# ignores indentations between strings, easy on the eye
str2 = "The alien gasps and says, 'Oh, this is it.  I will die! \n"\
       "Tell my 2.4 million larvae that I loved them... \n"\
       "Good-bye, cruel universe.'"
# using just triple quotes, still tough to read?
# note: newline characters are taken care of
str3 = """The alien gasps, 'Oh, this is it.  I will die!
Tell my 2.4 million larvae that I loved them...
Good-bye, cruel universe.' """
# using triple quotes and line continuation (\)
# the text lines up properly and 
# IMHO the easiest to write and read
str4 = """\
The alien gasps and says, 'Oh, this is it.  I will die!
Tell my 2.4 million larvae that I loved them...
Good-bye, cruel universe.' """
# note: indentations become part of the string
str5 = """The alien gasps, 'Oh, this is it.  I will die!
       Tell my 2.4 million larvae that I loved them...
       Good-bye, cruel universe.' """
# gee, one more way to do a multiline string with the + concatinator ...
str6 = "The alien gasps and says, 'Oh, this is it.  I will die! \n"
str6 = str6 + "Tell my 2.4 million larvae that I loved them... \n"
str6 = str6 + "Good-bye, cruel universe.'"
# another variation using +
str7 = "The alien gasps and says, 'Oh, this is it.  I will die! \n"
str8 = "Tell my 2.4 million larvae that I loved them... \n"
str9 = "Good-bye, cruel universe.'"
str10 = str7 + str8 + str9
# will work with Python2 and Python3 
print('-'*60)  # pretty up with 60 dashes

Since Python does not need type declarations, I wanted to test the numeric capacity for integers with a program that calculates factorials since they quickly give very large numbers. I stopped at the factorial of 69 only because the line started wrapping.

# check the numeric range of Python with huge factorials
# factorial(69) still checks out accurately! Has 98 digits in it!
# 171122452428141311372468338881272839092270544893520369393648040923257279754140647424000000000000000

def fact(n):
    """recursive function, returns the factorial of n"""
    if n == 0:
        return 1
        k = n * fact(n-1)
        return k

for k in range(1, 70):
    # use % string formatting, works with Python2 and Python3
    sf = "factorial of %d = %d" % (k, fact(k))
    print( sf )

This boggles my mind since it took all sorts of hoops to try this with C++ earlier in my life. In C++ the unsigned long integer fizzles out at a measly 4.3 billion. Those are only ten digits!

Here is another little number trick I picked up from one of the forums. This poor fellow wanted to do it in C, but the old compiler just couldn't handle the number of digits in the result. No sweat for Python ...

# another little number trick ...

a = 111111111   # that's nine ones

print( "%d * %d = %d" % (a, a, a * a) )

"""my result -->
111111111 * 111111111 = 12345678987654321

Edited by vegaseat: [code=python] tag. Python3 ready


This shows you how to mimic a C struct type with an empty Python class ...

# create a structure similar to C struct using an empty class
class Employee(object):
john = Employee() # Create empty employee record/struct
ted = Employee()
mark = Employee()
# fill the fields of the record/struct
john.name = 'John Johnson'
john.dept = 'computer lab'
john.salary = 3000
ted.name = 'Ted Tetris'
ted.dept = 'human resources'
ted.salary = 5000
mark.name = 'Mark Marksman'
mark.dept = 'shipping area'
mark.salary = 3200
# this works like a struct or record
print( "%s works in the %s and earns $%s/month" % \
    (john.name, john.dept, john.salary) )
# or use a list of Employee() instances ...
empList = [john, ted, mark]
for emp in empList:
    print( "%s works in the %s and earns $%s/month" % \
        (emp.name, emp.dept, emp.salary) )

"""my output -->
John Johnson works in the computer lab and earns $3000/month
John Johnson works in the computer lab and earns $3000/month
Ted Tetris works in the human resources and earns $5000/month
Mark Marksman works in the shipping area and earns $3200/month

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


While Python offers flexible container data structures, such as lists and dictionaries, it is occasionally helpful to create our own. Suppose, for example, that we wanted to create a data structure with two dictionaries: one for key-value pairs where len(key) is even, and one for key-value pairs where len(key) is odd. We would like to allow the Python builtins, such as str(), len(), container[key], etc, to access our objects in a meaningful way, and Python lets us do this via container-emulation methods:

import sys
# -- The Container class
class Container:
     # Instance variables:
     # self.even is a dictionary which stores key-value pairs
     # where the key has an even length
     # self.odd is a dictionary which stores key-value pairs
     # where the key has an odd length
     # Initialize new Container objects
     def __init__(self):
          self.even = dict(); self.odd = dict()
     # __len__() lets you use len() to evaluate this object
     def __len__(self):
          return len(self.even)+len(self.odd)
     # __repr__() lets you use str() to evaluate this object
     def __repr__(self):
          return str(self.even)+"\n"+str(self.odd)
     # __getitem__ allows evaluation of container[key]
     def __getitem__(self, key):
          if len(key)%2 == 0: return self.even[key]
          else: return self.odd[key]
     # __setitem__ allows assignment to container[key]
     def __setitem__(self, key, value):
          if len(key)%2 == 0: self.even[key] = value
          else: self.odd[key] = value
     # __delitem__ lets you use del container[key] to remove keys
     def __delitem__(self, key):
          if len(key)%2 == 0: del self.even[key]
          else: del self.odd[key]
     # __contains__ lets you use "key in container" boolean expressions
     def __contains__(self, key):
          return (key in self.even or key in self.odd)
     # __iter__ lets you iterate through the items via "for x in container"
     def __iter__(self):
          ret = []
          return ret.__iter__()
# -- The main function (diagnostic)
def main(args):
    # __init__
    c = Container()
    # __setitem__
    print "Adding key-value pairs\n"
    c["Laverne"] = "Shirley"
    c["Ozzie"] = "Harriet"
    c["Abbott"] = "Costello"
    c["Carl"] = "Steve"
    # __len__
    print "The length of our container is", len(c), "\n"
    # __repr__
    print "One string representation is:\n", str(c), "\n"
    # __getitem__
    print "The partner of Abbott is", c["Abbott"], "\n"
    # __delitem__
    del c["Laverne"]
    print "We have just deleted the Laverne:Shirley key-value pair"
    print "The new length is", len(c)
    print "Now, the container looks like\n", str(c), "\n"
    # __contains__
    print "Is the key 'Batman' in our container?"
    if "Batman" in c: print c["Batman"]
    else: print "Sorry, Boy Wonder"
    print "Is the key 'Ozzie' in our container?"
    if "Ozzie" in c: print "Yes, and it is", c["Ozzie"], "\n"
    else: print "No Ozzies here", "\n"
    # __iter__
    print "Let's iterate through all available keys and their values"
    for x in c: print x, "\t", c[x]
# -- The following code executes upon program invocation
if __name__ == "__main__": main(sys.argv)

What this gives you is the freedom to define your own container data structures, and then use them just like you would use Python-supplied containers. Pretty snazzy!

The trick here is that you can define these functions any way you want. For example, your __repr__ method could always return "fish" regardless of the values of the object's instance variables - but that would be counter-intuitive, because programmers generally expect str() to return a string value that represents, at least in part, the internal state of the object. So beware!

Also, the __iter__ method I provided doesn't really build an iterator object - it just compiles a list of keys, then borrows the iterator from that. For more information on iterators and generators, see van Rossum's reference manual.


A look at a simple Python class example for the OOP beginner ...

# looking at a simple Python class
# a class combines a number of methods/functions that belong together
class Box(object):
    class names by convention are capitalized, (object) is 
    a basic class inheritance signifying the new style class
    def __init__(self, depth, height, width):
        """__init__() is called first (acts as Constructor)
        brings in data from outside the class and makes it
        usable within the class via the instance object self.
        Look at self as the data carrier within the class.
        self.depth = depth
        self.height = height
        self.width = width
    def volume(self):
        """class methods have self as first argument"""
        return self.height * self.width * self.depth
    def surface(self):
        return 2*self.height*self.width + 2*self.height*self.depth + 2*self.width*self.depth
# construct an instance of a 10x10x10 box and reference it with box1
box1 = Box(10, 10 ,10)
print( "A 10x10x10 box has a volume of", box1.volume() )
print( "and a surface area of", box1.surface() )
print('')  # empty line in Python3 and Python2
print( "Let's change the depth to 5" )
# construct an instance of a 5x10x10 box and reference it with box2
box2 = Box(5, 10 ,10)
print( "A 5x10x10 box has a volume of", box2.volume() )
print( "and a surface area of", box2.surface() )
print( "Optional tests for the inquisitive folks:" )
print( "box1 =", box1 )
print( "box2 =", box2 )
print( "The depth of box2 is", box2.depth )
# Can we set the box dimensions directly?  Let's try it.
box1.depth = 5
box1.height = 5
box1.width = 5
print( "Box1 volume after setting box1 dimensions to 5x5x5 =", box1.volume() )

Here class Box inherits the most basic container class object (actually just a place holder), this is the newer class writing convention, adding (object) is "still" optional.

With Python3 object is inherited by default.

Edited by vegaseat: [code=python] tag, Python3 ready


The question came up in the forum how to represent an integer as a hexadecimal. There were two obvious ways to do this, the hex() function and the format operator %X. The resulting strings 0xac23b and AC23B look different. If you have to display the result, AC23B might be your choice. Otherwise speed might be important, particularly, if you call the function a lot. Here is a way to measure speed ...

# two different ways to represent integer 705083 as a hexadecimal 
# number, 0x is the official prefix for a hexnumber
# the results appear different, but both are of type string 
# and change back to base 10 properly
# using the hex() function
hex1 = hex(705083)
print( hex1, type(hex1), int(hex1,16) )  
# using the format operator %
hex2 = "%X" % 705083
print( hex2, type(hex2), int(hex2, 16) )  
# let's time the two options ...
import timeit

print( "Timing study ..." )
t = timeit.Timer('hex(705083)')
elapsed = (10 * t.timeit(number=100000))
print( 'hex(705083) takes %0.3f microseconds/pass' % elapsed )
t = timeit.Timer('"%X" % 705083')
elapsed = (10 * t.timeit(number=100000))
print( 'Format operator takes %0.3f microseconds/pass' % elapsed )

"""my output (Python 3.1) -->
0xac23b <class 'str'> 705083
AC23B <class 'str'> 705083
Timing study ...
hex(705083) takes 0.591 microseconds/pass
Format operator takes 0.048 microseconds/pass

Writing a module and testing it ...

# save as  den2bin.py  and use  
# import den2bin  in any program that needs it
# call the function with something like  den2bin.denary2binary(76)
# (it's easiest to keep this file in the working folder)
def denary2binary(n):
    convert denary integer n (base 10) to binary string bStr (base 2)
    bStr = ''
    if n <= 0: 
        return '0'
    while n > 0:
        bStr = str(n % 2) + bStr
        n = n >> 1
    return bStr
# the test code below only runs when used as a standalone program
# let's say you save this module as den2bin.py 
# when you import den2bin  the __name__ namespace would now be  
# 'den2bin'  and not '__main__' and the module test will be ignored
if __name__ == '__main__':
    print( denary2binary(255) )          # 11111111
    # convert back to test it
    print( int(denary2binary(255), 2) )  # 255
    # with Python3 you can simply use builtin function bin()
    #print( bin(255), type(bin(255)) )  # 0b11111111 <class 'str'>

This is kind of neat:

# assigning the same value to several variable names:
a = b = c = 7

print( a )  # 7
print( c )  # 7 

# contents of local dictionary ...
print( vars() )  # {'a': 7, 'c': 7, 'b': 7, ... }
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.