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.
# a function to format to $ currency
def formatDollar(amount):
return "$%.2f" % amount
print formatDollar(123.9 * 0.07)
print formatDollar(19)
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/downl...p.exe&74856058
Boa uses wxPython and works with Python2.5 and wxPython2.8 on Windows XP and Vista.