Python 101 - Introduction to Python - Part 2
by Dave KuhlmanRexx.com
Wednesday, 3rd August 2005
Simple Statements
The print statement sends output to stdout.
Here are a few examples:
print obj1, obj2, obj3
print "My name is %s" % name
Notes:
- To print multiple items, separate them with commas. The print statement inserts a blank between objects.
- The print statement automatically appends a newline to output. To print without a newline, add a comma after the last object, or use "sys.stdout", for example:
print 'Output with no newline',
which will append a blank, or:
import sys
sys.stdout.write("Some output")
- To re-define the destination of output from the print statement, replace sys.stdout with an instance of a class that supports the write method. For example:
import sys
class Writer:
def __init__(self, filename):
self.filename = filename
def write(self, msg):
f = file(self.filename, 'a')
f.write(msg)
f.close()
sys.stdout = Writer('tmp.log')
print 'Log message #1'
print 'Log message #2'
print 'Log message #3'
More information on the print statement is at http://www.python.org/doc/current/ref/print.html.
Note: Note to Jython users - Jython does not appear to support the file constructor for files. In the above example, replace file with open.
import
The import statement makes a module and its contents available for use.
Here are several forms of the import statement:
- import test
- Import module test. Refer to x in test with "test.x".
- from test import x
- Import x from test. Refer to x in test with "x".
- from test import *
- Import all objects from test. Refer to x in test with "x".
- import test as theTest
- Import test; make it available as theTest. Refer to object x with "theTest.x".
A few comments about import:
- The import statement also evaluates the code in the imported module.
- But, the code in a module is only evaluated the first time it is imported in a program. So, for example, if a module mymodule.py is imported from two other modules in a program, the statements in mymodule will be evaluated only the first time it is imported.
- If you need even more variety that the import statement offers, see the imp module. Documentation at http://www.python.org/doc/current/lib/module-imp.html. Also see the __import__ built-in function. Documentation at http://www.python.org/doc/current/lib/built-in-funcs.html.
More information on import at http://www.python.org/doc/current/ref/import.html.
assert
Use the assert statement to place error checking statements in you code. Here is an example:
arg1 = float(arg1)
arg2 = float(arg2)
assert arg2 != 0, 'Bad dividend -- arg1: %f arg2: %f' % (arg1, arg2)
ratio = arg1 / arg2
print 'ratio:', ratio
When arg2 is zero, running this code will produce something like the following:
File "tmp.py", line 22, in ?
main()
File "tmp.py", line 18, in main
test(args[0], args[1])
File "tmp.py", line 8, in test
assert arg2 != 0, 'Bad dividend -- arg1: %f arg2: %f' % (arg1, arg2)
AssertionError: Bad dividend -- arg1: 2.000000 arg2: 0.000000
A few comments:
- Notice that the trace-back identifies the file and line where the test is made and shows the test itself.
- If you run python with the optimize options (-O and -OO), the assertion test is not performed.
- The second argument to assert is optional.
global
The problem -- Imagine a global variable NAME. If, in a function, the first mention of that variable is "name = NAME", then I'll get the value of the the global variable NAME. But, if, in a function, my first mention of that variable is an assignment to that variable, then I will create a new local variable, and will not refer to the global variable at all. Consider:
def show_global():
name = NAME
print '(show_global) name: %s' % name
def set_global():
NAME = 'Nectarine'
name = NAME
print '(set_global) name: %s' % name
show_global()
set_global()
show_global()
Running this code produces:
(set_global) name: Nectarine
(show_global) name: Peach
The set_global modifies a local variable and not the global variable as I might have intended.
The solution -- How can I fix that? Here is how:
def show_global():
name = NAME
print '(show_global) name: %s' % name
def set_global():
global NAME
NAME = 'Nectarine'
name = NAME
print '(set_global) name: %s' % name
show_global()
set_global()
show_global()
Notice the global statement in function set_global. Running this code does modify the global variable NAME, and produces the following output:
(set_global) name: Nectarine
(show_global) name: Nectarine
Comments:
- You can list more than one veriable in the global statement. For example:
global NAME1, NAME2, NAME3
Options:
Printer Friendly
Email Friend
Dave Kuhlman has worked for many years on a variety of software development projects, in several programming languages, and on more than one platform. Because of Python's clear syntax, developer friendliness, and broad utility, Dave focuses his energy on the Python language, on systems built with Python, and on developing documentation and training materials for those systems. Dave's current work involves XML processing in Python as well as the development of tools and documentation for Zope and the CMSs (content management systems) that run on top of Zope, Dave's current platform is Debian GNU/Linux; he has installed and administers a small network composed of several Linux boxes behind a Linux router/gateway. More information about Dave's work can be found at http://www.rexx.com/~dkuhlman.
