Helping ordinary people create extraordinary websites!
HOME TUTORIALS SCRIPTS WEB HOSTING BLOG FORUM
Get Our Newsletter
Email:

Python 101 - Introduction to Python

By Dave Kuhlman
2005-07-02


Simple Statements

Simple Statements

print

The print statement sends output to stdout.

Here are a few examples:

print obj

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:

def test(arg1, arg2):

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:

Traceback (most recent call last):

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:

NAME = "Peach"


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:

(show_global) name: Peach

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

NAME = "Peach"


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:

(show_global) name: Peach

(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


Tutorial Pages:
» Python 101 -- Introduction to Python
» Interactive Python
» Data Types
» Simple Statements
» Control Structures
» Organization


Copyright (c) 2003 Dave Kuhlman


 | Bookmark
Related Tutorials:
» Python and Java - A Side by Side Comparison
» Learn Python in 10 Minutes
» Python 201 - (Slightly) Advanced Python Topics
» Google Sitemaps
» Python 101
» Python vs. Perl

Ask A Question
characters left.