1,105,644 Community Members

Starting Python

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
22
 

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
You can download the version you like free from: www.python.org
As of 2013 stick with Python27 or Python33.
Selfextracting MS Installer files have a .msi extension and contain the version number, for instance python-3.3.2.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:
http://getpython3.com/diveintopython3/
(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 I ended up with a C:\Python33 folder after the installation. The first step is to create a subfolder (subdirectory) for all your test programs, like D:\Python33\Atest33.

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
C:\Python33\Lib\idlelib\idle.pyw

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'.

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

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) is at:
http://www.pythonware.com/products/pil/index.htm

The PyGame module for game programming is at:
http://www.pygame.org

Also look at this site for other Python third party modules:
http://www.lfd.uci.edu/~gohlke/pythonlibs/
(mostly binary Windows installers)

A detailed and interesting essay about Python's creation and architecture:
http://stride-online.com/filestorage/Python.pdf
Another good introduction into the design philosophy of Python:
http://en.wikipedia.org/wiki/Python_programming_language

Google offers a great Starting Python Class online:
http://code.google.com/edu/languages/google-python-class/

Nice humor ...
http://xkcd.com/353/

A Foolish Consistency is the Hobgoblin of Little Minds ...
for recommended Python code writing style see:
http://www.python.org/dev/peps/pep-0008/

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
http://pythontutor.com/

On my iPad I use an app called "Pythonista" that does a nice job with Python 2.7 (also has PIL).

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

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!

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
9
 

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

# start the program with this function call
main()

"""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():
    print('f1')
    # call function f2
    f2()

def f2():
    print('f2')
    f3()

def f3():
    print('f3')

# all function have been defined
# this will work fine
f1()

Here a call is made before define ...

def f1():
    print('f1')
    # call function f2
    f2()

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

def f2():
    print('f2')
    f3()

def f3():
    print('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:
http://wiki.python.org/moin/PythonEditors

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)
http://pype.sourceforge.net/index.shtml

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:
http://mmm-experts.com/Downloads.aspx?ProductId=4

This free IDE is more general, but has a truckload full of real nice programmer's features:
http://www.pspad.com/en/

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:
http://sourceforge.net/project/downloading.php?group_id=1909&use_mirror=osdn&filename=boa-constructor-0.6.1.bin.setup.exe&74856058
Boa uses wxPython and works with Python2.5 or 2.6 and wxPython2.8 on Windows XP and Vista.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

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]
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

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

# 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")
 
# dito for the math module
help("math")
 
# file stuff ...
help("file")
 
# down to method/function level ...
help("os.read")

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:
http://www.daniweb.com/forums/post1306519.html#post1306519

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:
http://www.python.org/peps/pep-0008.html

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
5
 

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()
textf.close()

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
help("string.split")

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

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
    try:
      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.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

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

try:
    # 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
label1.pack() 
 
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:
http://infohost.nmt.edu/tcc/help/pubs/tkinter/index.html

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:
http://wiki.wxpython.org/index.cgi/AnotherTutorial

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

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

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
        try:
            data = float(sin)
            data_list.append(data)
        except ValueError:
            print( "Enter numeric data!" )
 
print('')
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): "
try:
    # 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!

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

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.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

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)
file.close()
 
# load the file back into a list 
file = open("list1.dat", "rb")
myList2 = pickle.load(file)
file.close()
 
# 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.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

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
 
calendar.prcal(2005)

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 ..." )
print('')
# Python3 uses input() instead of raw_input()
year = int(raw_input("Enter the year (eg. 2005): "))
print('')
calendar.prcal(year)
print('')
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
  Py_Initialize();
 
  // 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
  Py_Finalize();
 
  cin.get();  // console wait
  return 0;
}
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
3
 

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"):
        fileList.append(filename)
 
# 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.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
2
 

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
        continue
    else:
        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!

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

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/'
try:
    fileHandle = urllib2.urlopen(urlStr)
    str1 = fileHandle.read()
    fileHandle.close()
    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()
fp.close()

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

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
    else:
        return false
 
if isSSL:
    print( "We have a SSL connection" )
else:
    print( "No SSL connection" )

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

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

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!

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

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):
    print(k)
Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

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.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
1
 

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)
random.shuffle(charList)
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.

Member Avatar
vegaseat
DaniWeb's Hypocrite
6,984 posts since Oct 2004
Reputation Points: 1,544 [?]
Q&As Helped to Solve: 1,872 [?]
Skill Endorsements: 67 [?]
Moderator
 
0
 

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!

You
Post:
Start New Discussion
View similar articles that have also been tagged: