Log in / Register
Home arrow Computer Science arrow Understanding Network Hacks
< Prev   CONTENTS   Next >

3.6 Control Structures

By now our programs runs top down without taking shortcuts or making any decisions. Time to change that!

The first control structure lstinlineif checks the truth of an expression. In most cases this it examines if a variable has a certain value or if the length of a list is bigger than zero.

a = "mooh"

if a == "mooh": print "Jippie"

A short note about truth in Python: The data type None and an empty string or list are both equal to False! The following examples are therefore all untrue. You should remember this or write it down on one of these famous yellow stickies decorating most monitors in the world.

a = []

if a: print "Hooray"

b = None

if b: print "Donald has luck"

c = ""

if c: print "I love rain"

If the checked expression is untrue one could execute code in the else block.

list = [range(10)]

if len(list) < 0: print ":("


print ":)"

If you have more than one condition to test on your list you can define more using elif, but be aware that all conditions are checked in the order they are specified and the first that is true wins.

list = [range(10)]

if len(list) < 0: print ":("

elif len(list) > 0 and len(list) < 10: print ":)"


print ":D"

The last example also shows how you can combine conditions with so called boolean operators. You just chain them with and and or to define if both or just one condition has to be true to make the whole expression true. The operator not negates an condition. Additionally it should be noted that you can group expressions by using round brackets and you can combine as many conditions as you like demonstrated by the next example:

a = 23

b = 42

if (a < 10 and b > 10) or (a > 10 and b < 10) or

( (a and not b) and a == 10): do_something_very_complicated()

The last control structures we discuss here are loops. Python compared to other languages only knows two of them for and while. Both ensure that a certain code block gets executed over and over again and differ only in their cancel condition.

A for loops runs till the end of an iterable data type like a list, tupel, set etc. is reached.

books = ('the art of deception', 'spiderman', 'firestarter')

for book in books: print book

A nice usage of a for loop is to output the contents of a file:

for line in open("test.txt"): print line

The while loop in contrast runs as long as the condition defined in its head is true.

x = 1

while x < 10:

print "%s" % x x = x + 1

3.7 Modules

The large Python community has written a module for nearly all the problems on earth. You can download them for free including their source code and utilize them in your own programs. In the following chapters we will make extensive use of Pythons module system. You load a module with the help of the import keyword.

import sys

print sys.version sys.exit(1)

If you would like to apply functions without prepending their module name you must import them as follows:

from sys import exit exit(1)

A special solution to import all functions of a module exists via * but the author advises not using, because it can lead to ugly, very hard to debug name collision.

from sys import * exit(1)

Thanks to Python's “batteries included” philosophy you get a huge collection of modules directly included into every Python installation, the so called standard library. It has solutions for a wide variety of tasks like access to the operating and file system (sys and os), HTTP and web access (urllib, urllib2, httplib, htmllib and cookielib), FTP (ftplib), Telnet (telnetlib), SMTP (smtplib) and much more. It pays out to poke in the documentation either online on or by typing pydoc <module> into the console.

Last but not least let us write a module of our own. Its as easy as creating a directory (e.g. mymodule) and put a file named init .py into it. init .py signalizes Python that this directory should be treated as a package and can initialize the import of your module (what we wont cover here). Create another file in the directory called and define the function add() as described in Sect. 3.5. That's it! Now you can use your module as follows:

from mymodul.test import add print add(1, 2)

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
Business & Finance
Computer Science
Language & Literature
Political science