16.01.2014 Views

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

Beginning Python - From Novice to Professional

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

570 APPENDIX B ■ PYTHON REFERENCE<br />

The for Statement<br />

The for statement is used for repeated execution (looping) over the elements of sequences or<br />

other iterable objects (objects having an __iter__ method that returns an itera<strong>to</strong>r). It may<br />

include an else clause (which is executed if the loop finishes normally, without any break or<br />

return statements, for instance).<br />

Example:<br />

for i in range(10, 0, -1):<br />

print i<br />

print 'Ignition!'<br />

The try Statement<br />

The try statement is used <strong>to</strong> enclose pieces of code where one or more known exceptions may<br />

occur, and enables your program <strong>to</strong> trap these exceptions and perform exception handling<br />

code if an exception is trapped.<br />

Example:<br />

try:<br />

1/0<br />

except ZeroDivisionError:<br />

print "Can't divide anything by zero."<br />

Function Definitions<br />

Function definitions are used <strong>to</strong> create function objects and <strong>to</strong> bind global or local variables <strong>to</strong><br />

these function objects.<br />

Example:<br />

def double(x):<br />

return x*2<br />

Class Definitions<br />

Class definitions are used <strong>to</strong> create class objects and <strong>to</strong> bind global or local variables <strong>to</strong> these<br />

class objects.<br />

Example:<br />

class Doubler:<br />

def __init__(self, value):<br />

self.value = value<br />

def double(self):<br />

self.value *= 2

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!