GIDNetwork > Beginning Python Tutorial (Part 8)
« Naming Conventions A dedicated server for GIDNetwork sites »

Beginning Python Tutorial (Part 8)

by: crystalattice - Nov 03, 2005

Basic Statements

Now that we know how Python uses it's fundamental data types, let's talk about how to use them. Python is nominally a procedure-based language but as we'll see later, it also functions as an object-oriented language. As a matter of fact, it's similar to C++ in this aspect; you can use it as either a procedural or OO language or combine them as necessary.

The following is a listing of Python statements, borrowed from O'Reilly's Learning Python.

Generic Code Example:

Statement 			Role 					Examples 
Assignment 		Creating references 		curly, moe, larry = 'good', 'bad', 'ugly' 
Calls 			Running functions 		stdout.write("spam, ham, toast\n") 
Print 			Printing objects 		print 'The Killer', joke 
If/elif/else 		Selecting actions 		if "python" in text: print text 
For/else 		Sequence iteration 		for X in mylist: print X 
While/else 		General loops 		        while 1: print 'hello' 
Pass 			Empty placeholder 		while 1: pass 
Break, Continue 	Loop jumps 		        while 1:          if not line: break 
Try/except/finally 	Catching exceptions 	        try: action() except: print 'action error' 
Raise 			Triggering exception 	        raise endSearch, location 
Import, From 	        Module access			import sys; from sys import stdin 
Def, Return 		Building functions 		def f(a, b, c=1, *d): return a+b+c+d[0] 
Class 			Building objects 		class subclass: staticData = [] 
Global 		        Namespaces 			def function(): global X, Y; X = 'new' 
Del 			Deleting things 		del data[k]; del data [i:j]; del obj.attr 
Exec 			Running code strings		yexec "import" + modName in gdict, ldict 
Assert 		        Debugging checks 		assert X > Y 


Assignment is similar to other languages, so I won't cover it in depth. Suffice it to say, assignment is basically putting the target name on the left of an equals sign and the object you're assigning it from, on the right. There's only a few things you need to remember:

Assignment creates object references.
Assignment acts like pointers in C since it doesn't copy objects, just creates a reference to an object.

Names are created when first assigned
Names don't have to be "pre-declared"; Python creates the variable name when it's first created. But as you'll see, this doesn't mean you can call on a variable that hasn't been assigned an object yet. If you call a name that hasn't been assigned yet, you'll get an exception error.

Assignment can be created either the standard way spam = "SPAM", via multiple target spam = ham = "Yummy", with a tuple spam, ham = "lunch", "dinner", or with a list [spam, ham] = ["yum", "YUM"].

The final thing to mention about assignment is that a name can be reassigned to different objects. Since a name is just a reference to an object and doesn't have to be declared, you can change it's "value" to anything. For example:

Generic Code Example:

>>>x = 0		#x is linked to an integer
>>>x = "spam"	        #now it's a string
>>>x = [1, 2, 3]	#now it's a list


Python expressions can be used as statements but since the result won't be saved, expressions are usually used to call functions/methods and for printing values at the interactive prompt.

Here's the typical format:

  • spam(eggs, ham) #function call

  • spam.ham(eggs) #method call

  • spam #interactive print

  • spam < ham and ham != eggs #compound expression

  • spam < ham < eggs #range test

The range test above lets you perform a Boolean test but in a "normal" fashion; it looks just like a comparison from math class.


Printing in Python is extremely simple. Using print writes the output to the C stdout stream and normally goes to the console unless you redirect it to another file.

Printing, by default, adds a space between items separated by commas and adds a linefeed at the end of the output stream. To suppress the linefeed, just add a comma at the end of the print statement:

Generic Code Example:

print lumberjack, spam, eggs,

To suppress the space between elements, just concatenate them when printing:

Generic Code Example:

print "a" + "b"

if Tests

The if statement works the same as other languages. The only difference is the else/if as shown below:

Generic Code Example:

if <test1>:               # if test 
    <statements1>         # associated block 
elif <test2>:             # optional elif's 
else:                     # optional else 

Unlike C, Pascal, and other languages, there isn't a switch or case statement in Python. You can get the same functionality by using if/elif tests, searching lists, or indexing dictionaries. Since lists and dictionaries are built at runtime, they can be more flexible. Here's an equivalent switch statement using a dictionary:

Generic Code Example:

>>> choice = 'ham' 
>>> print {'spam':  1.25,            # a dictionary-based 'switch' 
...       'ham':   1.99,            #use has_key() test for default case 
...       'eggs':  0.99, 
...       'bacon': 1.10}[choice] 

while Loops

The Python while statement is, again, similar to other languages. Here's the main format:

Generic Code Example:

while <test>:             # loop test 
    <statements1>         # loop body 
else:                     # optional else 
    <statements2>         # run if didn't exit loop with break 

break and continue work the exact same as in C. The equivalent of C's empty statement (a semicolon) is the pass statement, and Python includes an else statement for use with breaks. Here's a full-blown while example loop:

Generic Code Example:

while <test>: 
    if <test>: break        # exit loop now, skip else 
    if <test>: continue     # go to top of loop now 
	<statements>            # if we didn't hit a 'break'

for Loops

The for loop is a sequence iterator for Python. It will work on nearly anything: strings, lists, tuples, etc. I've talked about for loops before so I won't get into much more detail about them. The main format is below:

Generic Code Example:

for <target> in <object>:   # assign object items to target 
    if <test>: break        # exit loop now, skip else 
    if <test>: continue     # go to top of loop now 
    <statements>            # if we didn't hit a 'break'

From Learning Python:

When Python runs a for loop, it assigns items in the sequence object to the target, one by one, and executes the loop body for each. * The loop body typically uses the assignment target to refer to the current item in the sequence, as though it were a cursor stepping through the sequence. Technically, the for works by repeatedly indexing the sequence object on successively higher indexes (starting at zero), until an index out-of-bounds exception is raised. Because for loops automatically manage sequence indexing behind the scenes, they replace most of the counter style loops you may be used to coding in languages like C.

Related to for loops are range and counter loops. The range function auto-builds a list of integers for you. Typically it's used to create indexes for a for statement but you can use it anywhere.

Generic Code Example:

>>> range(5), range(2, 5), range(0, 10, 2) 
([0, 1, 2, 3, 4], [2, 3, 4], [0, 2, 4, 6, 8]) 

As you can see, a single argument gives you a list of integers, starting from 0 and ending at one less than the argument. Two arguments gives a starting number and the max value while three arguments adds a stepping value, i.e. how many numbers to skip between each value.

Well, that's it for this installment. As you can see, Python is a pretty simple language that "automates" many of the features you'd have to code by hand in other languages. Next time I'll discuss using procedural-style functions in Python followed by a more in-depth look at modules.

Would you like to comment? This story has been viewed 22,764 times.
« Naming Conventions A dedicated server for GIDNetwork sites »


Copyright © GIDNetwork™ 2001 - 2023

Another website by J de Silva

Page generated in : 0.00765 sec.