python prog

Upload: nishad-patil

Post on 07-Aug-2018

230 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/19/2019 Python Prog

    1/98

    From Wikibooks, the open-content textbooks collection

    P YTHON PROGRAMMING

    by Wikibooks contributors

    http://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    2/98

    Python Programming

    Permission is granted to copy, distribute and/or modify this document under the terms

    of the GNU Free Documentation icense, !ersion "#$ or any later %ersion published by

    the Free &oft'are Foundation( 'ith no )n%ariant &ections, no Front-*o%er +exts, and no

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    3/98

    From Wikibooks, the open-content textbooks collection

    Contents

    )ntroduction########################################################################################################################################## $

    %er%ie'##########################################################################################################################################$

    Getting Python################################################################################################################################# 0

    )nteracti%e mode############################################################################################################################## 1

    earning to program in Python#############################################################################################################2

    *reating Python programs############################################################################################################### 2

    Using %ariables and math#################################################################################################################3

    Python conepts####################################################################################################################################""

    asic syntax################################################################################################################################### ""Data types###################################################################################################################################### "4

     Numbers####################################################################################################################################"5

    &trings####################################################################################################################################### "2

    ists########################################################################################################################################### $1

    +uples########################################################################################################################################$3

    Dictionaries############################################################################################################################### 0$

    &ets############################################################################################################################################ 04

    perators########################################################################################################################################06Flo' control###################################################################################################################################47

    Functions########################################################################################################################################44

    &coping########################################################################################################################################## 42

    8xceptions######################################################################################################################################42

    )nput and output#############################################################################################################################1"

    9odules######################################################################################################################################### 11

    *lasses########################################################################################################################################### 159eta*lasses################################################################################################################################### 55

    :ocking the Python ;9odules

  • 8/19/2019 Python Prog

    4/98

    Python Programming

    OVERVIEW

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python is a high-le%el, structured, open-source programming language that can be used for a

    'ide %ariety of programming tasks# )t is good for simple Buick-and-dirty scripts, as 'ell as complex

    and intricate applications#

    )t is an interpreted programming language that is automatically compiled into bytecode before

    execution ;the bytecode is then normally sa%ed to disk, Cust as automatically, so that compilation

    need not happen again until and unless the source gets changed

  • 8/19/2019 Python Prog

    5/98

    From Wikibooks, the open-content textbooks collection

    GETTING PYTHON

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    )n order to program in Python you need the Python soft'are#

    Installing Python in Windows

    Go to http?//'''#python#org/do'nload/  or the cti%e&tate 'ebsiteE"  and get the proper

    %ersion for your platform# Do'nload it, read the instructions and get it installed#

    )n order to run Python from the command line, you 'ill need to ha%e the python directory in

    your P+# lternati%ely, you could use an )ntegrated De%elopment 8n%ironment ;)D8< for

    Python like DrPythonE$, ericE0, or Py&cripter E4#

    Installing Python in Unix

    Python is standard eBuipment in many Unix-like operating systems( Cust type which pythn

    to check for it# )f present, it may not be the latest, but it should be enough to get you started#

    )f its not installed, check your operating systems 'eb page for the proper package# Failing

    that, you 'ill need to do'nload the appropriate file from http?//'''#python#org/do'nload or the

    cti%e&tate 'ebsiteE1#

    )f you decide to compile Python from source, make sure you compile in the tk extension if you

    'ant to use )D8#

    n Debian based inux systems, you can do'nload it by starting the command line, changing

    to the superuser mode using su - and then by typing apt-get install python#

    Installing Python PyDE Pl!g"in #o$ E%li&se IDEHou can use the 8clipse )D8 as your Python )D8# +he only reBuirement is 8clipse and the

    8clipse PyD8! Plug-in#

    Go to http?//do'nload#eclipse#org/do'nloads and get the proper 8clipse )D8 %ersion for your

    http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Getting_Pythonhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Getting_Pythonhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Getting_Python&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://www.python.org/download/http://activestate.com/http://drpython.sourceforge.net/http://www.die-offenbachs.de/detlev/eric3.htmlhttp://mmm-experts.com/Products.aspx?ProductID=4http://www.python.org/downloadhttp://activestate.com/http://en.wikibooks.org/wiki/Using_Eclipsehttp://download.eclipse.org/downloadshttp://www.python.org/download/http://activestate.com/http://drpython.sourceforge.net/http://www.die-offenbachs.de/detlev/eric3.htmlhttp://mmm-experts.com/Products.aspx?ProductID=4http://www.python.org/downloadhttp://activestate.com/http://en.wikibooks.org/wiki/Using_Eclipsehttp://download.eclipse.org/downloadshttp://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Getting_Pythonhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Getting_Pythonhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Getting_Python&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    6/98

    Python Programming

    Python Mode #o$ E'a%s

    +here is also a python mode for 8macs 'hich pro%ides features such as running pieces of code,

    and changing the tab le%el for blocks# Hou can do'nload the mode athttp?//sourceforge#net/proCects/python-mode/

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikipedia.org/wiki/emacshttp://sourceforge.net/projects/python-mode/http://en.wikibooks.org/wiki/Python_Programming/Getting_Pythonhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Getting_Pythonhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Getting_Python&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikipedia.org/wiki/emacshttp://en.wikibooks.org/wiki/Python_Programminghttp://sourceforge.net/projects/python-mode/http://en.wikibooks.org/wiki/Python_Programming/Getting_Pythonhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Getting_Pythonhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Getting_Python&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Getting_Python&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    7/98

    From Wikibooks, the open-content textbooks collection

    INTERACTIVE MODE

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python has t'o basic modes? +he normal .mode. is the mode 'here the scripted and finished

    .py files are run in the python interpreter# )nteracti%e mode is a command line shell 'hich gi%es

    immediate feedback for each statement, 'hile running pre%iously fed statements in acti%e memory#

    s ne' lines are fed into the interpreter, the fed program is e%aluated both in part and in 'hole#

    +o get into interacti%e mode, simply type .python. 'ithout any arguments# +his is a good 'ay

    to play around and try %ariations on syntax# Python should print something like this?

    ! python"ythn 2.3.4 (#2, $%& 29 2004, 02:04:10)' 3.3.4 (*ebian 1:3.3.49) n lin%-2ype /help/, /cpyri&ht/, /creit/ r /licene/ r re inratin.>>>

    ;)f Python 'ouldnt run, make sure your path is set correctly# &ee Getting Python#<

    +he >>> is Pythons 'ay of telling you that you are in interacti%e mode# )n interacti%e mode

    'hat you type is immediately run# +ry typing 1+1 in# Python 'ill respond 'ith 2# )nteracti%e mode

    allo's you to test out and see 'hat Python 'ill do# )f you e%er feel the need to play 'ith ne'

    Python statements, go into interacti%e mode and try them out#

    sample interacti%e session?

    >>> 55>>> print 5*735>>> "hello" * 4hellhellhellhell>>> "hello".__class__ 

    o'e%er, you need to be careful in the interacti%e en%ironment# )f you arent confusion may

    ensue# For example, the follo'ing is a %alid Python script?

    if 1:print "True"

    http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Interactive_modehttp://en.wikibooks.org/wiki/Talk:Python_Programming/Interactive_modehttp://en.wikibooks.org/w/index.php?title=Python_Programming/Interactive_mode&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Programming:Python_Getting_Pythonhttp://en.wikibooks.org/wiki/Programming:Python_Getting_Pythonhttp://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Interactive_modehttp://en.wikibooks.org/wiki/Talk:Python_Programming/Interactive_modehttp://en.wikibooks.org/w/index.php?title=Python_Programming/Interactive_mode&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    8/98

    Python Programming

    you should ha%e entered 'as a blank line, to end the first ;i#e#, .if.< statement, before you started

    'riting the next print statement# For example, you should ha%e entered the statements as though

    they 'ere 'ritten?

    if 1:  print "True"

     print "one"

    >hich 'ould ha%e resulted in the follo'ing?

    >>> if 1:...  print "True"...r%e>>> print "one"*ne>>>

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming/Interactive_modehttp://en.wikibooks.org/wiki/Talk:Python_Programming/Interactive_modehttp://en.wikibooks.org/w/index.php?title=Python_Programming/Interactive_mode&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming/Interactive_modehttp://en.wikibooks.org/wiki/Talk:Python_Programming/Interactive_modehttp://en.wikibooks.org/w/index.php?title=Python_Programming/Interactive_mode&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Interactive_mode&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    9/98

    From Wikibooks, the open-content textbooks collection

    CREATING PYTHON PROGRAMS

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python programs are nothing more than text files, and they may be edited 'ith standard text

    editors#I

    )n >indo's, notepad 'ill be sufficient for a little 'hile, but you 'ill soon find that a more

     po'erful editor, such as %im, emacs, or pythons built-in )D8, )D8 makes editing much easier#

    )n Unix, nano or pico are respectable beginners editors, 'hile %im and emacs are used 'hen

    more po'er is needed#

    dditional editors exist that are Python friendly ;e#g#, use Python syntax highlighting

  • 8/19/2019 Python Prog

    10/98

    Python Programming

    Result

    +he program should print ell, wrl# *ongratulationsK Houre 'ell on your 'ay to

     becoming a Python programmer#

    Inter!ti"e #ode

    )nstead of python exiting 'hen the program is finished, you can use the -i flag to start an

    interacti%e session# +his can be "er$ useful for debuging and prototyping#

    pythn i hell.py

    Exer!ises

    • 9odify the hell.py program to say hello to a historical political leader ;or to da 

    o%elace

  • 8/19/2019 Python Prog

    11/98

    From Wikibooks, the open-content textbooks collection

    USING VARIA%&ES AND MATH

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Using a (a$ia)le

    variable is something 'ith a %alue that may change# )n Python, %ariables are strongly typed,

    meaning that if a %ariable has a number , it cant be treated as a string, or %ice %ersa# ere is a

     program that uses a %ariable?

    #;%r;bin;pythn

    nae = $a elaceprint /bye, / + nae +

    ;opsK ) used single Buotes for das name, then double Buotes around Goodbye# +hats M,

    ho'e%er, because these t'o Buotes do exactly the same thing in Python# +he only thing you cant do

    is mix them and try to make a string like this? /will nt wr?#<

    +his program isnt much use, of course# ut 'hat about %ariables that the program truly cant

    guess aboutL

    $aw*in&!t+,#;%r;bin;pythn

    print "leae enter y%r nae.nae = raw@inp%t()print w are y%, + nae + A

    ;>hats raw@inp%t() doingL 8%idently, its getting input  from you# &ee )nput and output#<

    f course, 'ith the po'er of Python at hand, the urge to determine ones mass in stone is nearly

    irresistible# concise program can make short 'ork of this task# &ince a stone is "4 pounds, andthere are about $#$ pounds in a kilogram, the follo'ing formula should do the trick?

    http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Using_variables_and_mathhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Using_variables_and_mathhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Using_variables_and_math&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Using_variables_and_math&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Using_variables_and_math&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Programming:Python_Numbershttp://en.wikibooks.org/wiki/Programming:Python_Stringshttp://en.wikibooks.org/wiki/Programming:Python_Input_and_outputhttp://en.wikibooks.org/wiki/Programming:Python_Numbershttp://en.wikibooks.org/wiki/Programming:Python_Stringshttp://en.wikibooks.org/wiki/Programming:Python_Input_and_outputhttp://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Using_variables_and_mathhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Using_variables_and_mathhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Using_variables_and_math&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Using_variables_and_math&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Using_variables_and_math&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    12/98

    Python Programming

    • >hen the pre%ious program asked for your name, you 'ere typing belo' the Buestion#

    +his time, youre typing at the end of the line that asks, /Bhat i y%r a in

    ?il&raA/# >hats happening here is that, normally, the print statement 'ill add a

    newline to the end 'hat youre printing# +hats 'hy the cursor 'ent to the next line in the pre%ious program# ut in this program, ) added a little comma to the end# +hat makes

    print omit the ne'line#

    • int() - this handy function takes a string, and returns a number# :emember 'hen you

    read that Python is strongly typedL Python 'ont allo' us to do math on a string# >hate%er

    you type is a string, e%en if it consists of digits# ut int() 'ill recognie a string made of

    digits and return a number#

    +he tr(mass@stone) in the print statement# )t turns out that you cant add togetherstrings and numbers( /D% wei&h / + a@tne Cust 'ouldnt 'ork# &o, 'e ha%e

    to take the number and turn it into a string# )ncidentally, E 'ould do the same thing as the

    str;< function, but that is deprecated#

    .o$'atting o!t&!t

    )n the pre%ious program, 'e used this line of code to print the result?

    print /D% wei&h / + tr(a@tne) + / tne./

    +here are a couple of problems 'ith this# First, it mixes up operators and Buotes, and can be a

    little tough to read# &econd, the number 'ont be printed %ery nicely, as the follo'ing example

    illustrates?

    ! .;?&2tne

    Bhat i y%r a in ?il&raA F5D% wei&h 10.214285G14285G14 tne.

     Not only is that much accuracy unCustified, it doesnt look nice# Pythons O operator comes to

    the rescue# )t allo's print-like formatting, in the form?

    STRING  H (ar&1, ar&2, ...) 

    +he string contains one format code for each argument# +here are se%eral types of format

    codes( see the strings section for a complete list#

    + i C t d th H f t d

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Programming:Python_Stringshttp://en.wikibooks.org/wiki/Programming:Python_Stringshttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    13/98

    From Wikibooks, the open-content textbooks collection

    %ASIC SYNTA'

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    +here are four fundamental concepts in Python#

    Case -ensiti(ity

    ll %ariables are case-sensiti%e# Python treats number and Number as seperate, unrelated

    entities#

    -&a%es and ta)s don/t 'ix

    ecause 'hitespace is significant, remember that spaces and tabs dont mix, so use only one or

    the other 'hen indenting your programs# common error is to mix them# >hile they may look the

    same in editor the interpreter 'ill read them differently and it 'ill result in either an error or

    unexpected beha%ior# o'e%er, tab are read as eBual to eight spaces, so changing your tab 'idth to6 in your editor helps if you find yourself freBuently making this mistake#

    O)0e%ts

    )n Python, like all obCect oriented languages, there are aggregations of code and data called

    bCects, 'hich typically represent the pieces in a conceptual model of a system#

    bCects in Python are created ;i#e#, instantiated< from templates called *lasses ;'hich are

    co%ered later, as much of the language can be used 'ithout understanding classes

  • 8/19/2019 Python Prog

    14/98

    Python Programming

    cannot be easily accessed# +here are t'o 'ays of delimiting regions in Python? 'ith functions or

    'ith modules# +hey each ha%e different 'ays of accessing the useful data that 'as produced 'ithin

    the scope from outside the scope# >ith functions, that 'ay is to return the data# +he 'ay to access

    names from other modules lead us to another concept#

    Na'es&a%es

    )t 'ould be possible to teach Python 'ithout the concept of namespaces because they are so

    similar to attributes, 'hich 'e ha%e already mentioned, but the concept of namespaces is one that

    transcends any particular programming language, and so it is important to teach# +o begin 'ith,

    there is a built-in function dir()  that can be used to help one understand the concept ofnamespaces# >hen you first start the Python interpreter ;i#e#, in interacti%e mode

  • 8/19/2019 Python Prog

    15/98

    From Wikibooks, the open-content textbooks collection

    '@@c@@, @@nae@@, ac, ain, atan, atan2, ceil, c, ch,e&ree, e,e-p, ab, lr, , re-p, hypt, le-p, l&, l&10,, pi, pw,

    raian, in, inh, Nrt, tan, tanh>>>

    )f you look closely, you 'ill notice that both the default namespace, and the math module

    namespace ha%e a @@name@@ obCect# +he fact that each layer can contain an obCect 'ith the same

    name is 'hat scope is all about# +o access obCects inside a namespace, simply use the name of the

    module, follo'ed by a dot, follo'ed by the name of the obCect# +his allo' us to differentiate

     bet'een the @@nae@@ obCect 'ithin the current namespace, and that of the obCect 'ith the same

    name 'ithin the ath module# For example?

    >>> print @@nae@@@@ain@@>>> print ath.@@nae@@ath>>> print ath.@@c@@hi %le i alway aailable. Kt prie acce t theatheatical %nctin eine by the tanar.>>> ath.pi3.141592F53589G931

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Basic_syntaxhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Basic_syntaxhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Basic_syntax&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Basic_syntax&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Basic_syntax&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Basic_syntaxhttp://en.wikibooks.org/wiki/Talk:Python_Programming/Basic_syntaxhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Basic_syntax&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Basic_syntax&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Basic_syntax&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    16/98

    Python Programming

    DATA TYPES

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Data types determine 'hether an obCect can do something, or 'hether it Cust 'ould not make

    sense# ther programming languages often determine 'hether an operation makes sense for an

    obCect by making sure the obCect can ne%er be stored some'here 'here the operation 'ill be

     performed on the obCect ;this type system is called static typing

  • 8/19/2019 Python Prog

    17/98

    From Wikibooks, the open-content textbooks collection

    bar/ e nt wr?, an/baL e nt wr? either./N%%- i ri&ht %t.

    +riple Buoted strings are like single Buoted strings, but can span more than one line# +heirstarting and ending delimiters must also match# +hey are entered 'ith three consecuti%e single or

    double Buotes, so

    wr?, an////// wr? a well,  b%t/bar/ e nt wr?, an

    ///baL e nt wr? either./N%%-// i ri&ht %t.

    +uples are entered in parenthesis, 'ith commas bet'een the entries?

    (10, Jary ha a little lab)

    lso, the parenthesis can be left out 'hen its not ambigouous to do so?

     10, whe leece wa a white a nw

     Note that one-element tuples can be entered by surrounding the entry 'ith parentheses and

    adding a comma like so?

    (thi i a t%pi t%ple,)

    ists are similar, but 'ith brackets?

    'abc, 1,2,3

    Dicts are created by surrounding 'ith curly braces a list of key,%alue pairs separated from each

    other by a colon and from the other entries 'ith commas?

    O hell: wrl, wei&ht: $rican r %rpeanA P

    ny of these composite types can contain any other, to any depth?

    (((((((((bb,),'Jary, ha, a, little, lab), O hell : wrl P ),),),),),),)

    http://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    18/98

    Python Programming

    NUM%ERSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python supports 4 types of Numbers, the int, the long, the float and the complex# Hou dont

    ha%e to specify 'hat type of %ariable you 'ant( Python does that automatically#

    •   Int: +his is the basic integer type in python, it is eBui%ilant to the hard'are c long for

    the platform you are using#

    •   Long: +his is a integer number thats length is non-limited# )n python $#$ and later, )nts

    are automatically turned into long ints 'hen they o%erflo'#•   Float:  +his is a binary floating point number# ongs and )nts are automatically

    con%erted to floats 'hen a float is used in an expression, and 'ith the true-di%ision /

    operator#

    •   Complex: +his is a complex number consisting of t'o floats# )t is in engineering style

    notation#

    )n general, the number types are automatically up cast in this order?

    )nt --J ong --J Float --J *omplex# the farther to the right you go, the higher the precedence#

     >>> - = 5 >>> type(-)  >>> - = 18GF8GF545F4F589G09G89098F95GF453 >>> type(-)

      >>> - = 1.34GF3 >>> type(-)  >>> - = 5 + 2Q >>> type(-) 

    o'e%er, some expressions may be confusing since in the current %ersion of python, using the

    / operator on t'o integers 'ill return another integer, using floor di%ision# For example, 1/$ 'illgi%e you $# Hou ha%e to specify one of the operands as a float to get true di%ision, e#g# 1/$# or 1#/$

    ;the dot specifies you 'ant to 'ork 'ith float< to ha%e $#1# +his beha%ior is deprecated and 'ill

    disappear in a future python release as sho'n from the from @@future@@ import#

    ;2

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming/Numbershttp://en.wikibooks.org/wiki/Talk:Python_Programming/Numbershttp://en.wikibooks.org/w/index.php?title=Python_Programming/Numbers&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Numbers&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Numbers&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming/Numbershttp://en.wikibooks.org/wiki/Talk:Python_Programming/Numbershttp://en.wikibooks.org/w/index.php?title=Python_Programming/Numbers&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Numbers&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Numbers&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    19/98

    From Wikibooks, the open-content textbooks collection

    STRINGSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    -t$ing 'ani&!lation

    Strin( o)ertions

    E*ulit$

    +'o strings are eBual if and only if they ha%e exactly the same contents, meaning that they are

     both the same length and each character has a one-to-one positional correspondence# 9any other

    languages test strings only for identity( that is, they only test 'hether t'o strings occupy the same

    space in memory# +his latter operation is possible in Python using the operator i#

    8xample?

    >>> a = hellR b = hell # $i&n hell t a an b.>>> print a == b # r%er%e>>> print a == hell #r%e>>> print a == /hell/ # (chice eliiter i %niprtant)r%e>>> print a == hell # (e-tra pace)ale

    >>> print a == ell # (wrn& cae)ale

    Nu#eri!l

    +here are t'o Buasi-numerical operations 'hich can be done on strings -- addition and

    multiplication# &tring addition is Cust another name for concatenation# &tring multiplication is

    repetiti%e addition, or concatenation# &o?

    >>> c = a>>> c + bab>>> c C 5aaaaa

    http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Stringshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Stringshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Strings&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming/Stringshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Stringshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Strings&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=new

  • 8/19/2019 Python Prog

    20/98

    Python Programming

    Indexin( nd Sli!in(

    9uch like arrays in other languages, the indi%idual characters in a string can be accessed by an

    integer representing its position in the string# +he first character in string s 'ould be sE7 and the nth

    character 'ould be at sEn-"#

    >>> = STana%U>>> '1VaW

    Unlike arrays in other languages, Python also indexes the arrays back'ards, using negati%e

    numbers# +he last character has index -", the second to last character has index -$, and so on#

    >>> '4VnW

    >e can also use QslicesR to access a substring of s# sEa?b 'ill gi%e us a string starting 'ith sEa

    and ending 'ith sEb-"#

    >>> '1:4

    VanaW

     Neither of these is assignable#

    >>> print >>> '0 = Xracebac? (t recent call lat):  ile SU, line 1, in Ayperrr: bQect e nt %pprt ite ai&nent>>> '1:3 = S%pUracebac? (t recent call lat):  ile SU, line 1, in Ayperrr: bQect e nt %pprt lice ai&nent>>> print

    utputs ;assuming the errors 'ere suppressed

  • 8/19/2019 Python Prog

    21/98

    From Wikibooks, the open-content textbooks collection

    leent: 1 2 3 4Kne-: 0 1 2 3 4  4 3 2 1

    &o, 'hen 'e ask for the E"?0 slice, that means 'e start at index ", and end at index 0, and takee%erything in bet'een them# )f you are used to indexes in * or Sa%a, this can be a bit disconcerting

    until you get used to it#

    Strin( !onstnts

    &tring constants can be found in the standard string module# 8ither single or double Buotes may

     be used to delimit string constants#

    Strin( #et+ods

    +here are a number of methods of built-in string functions?

    • !)itli,e 

    • !enter 

    • !ount 

    • decode

    • encode

    • ends'ith

    • ex)ndt-s 

    • .ind 

    • index 

    • islnu# • isl)+ 

    • isdi(it 

    • islower 

    • iss)!e 

    • istitle 

    • isu))er 

     /oin • l/ust 

    • lower 

    • lstri) 

    • re)l!e 

    • r.ind

    http://wikibooks.org/http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    22/98

    Python Programming

    nly emphasied items 'ill be co%ered#

    is0

    isalnum;

  • 8/19/2019 Python Prog

    23/98

    From Wikibooks, the open-content textbooks collection

    stri)1 rstri)1 lstri)

    :eturns a copy of the string 'ith the leading ;lstrip< and trailing ;rstrip< 'hitespace remo%ed#

    strip remo%es both#

    >>> = t ell, wrlnt >>> print   ell, wrl >>> print .trip()ell, wrl>>> print .ltrip()ell, wrl

      # en here>>> print .rtrip()  ell, wrl

     Note the leading and trailing tabs and ne'lines#

    &trip methods can also be used to remo%e other types of characters#

    iprt trin& = www.wi?ib?.r&print print .trip(w) # Yee all w r %tieprint .trip(trin&.lwercae) # Yee all lwercae letter r %tieprint .trip(trin&.printable) # Yee all printable character

    utputs?

    www.wi?ib?.r&.wi?ib?.r&.wi?ib?. 

     Note that string#lo'ercase and string#printable reBuire an import string statement

    l/ust1 r/ust1 !enterleft, right or center Custifies a string into a gi%en field sie ;the rest is padded 'ith spaces>> = >>>

    P h P i

    http://wikibooks.org/http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    24/98

    Python Programming

    >>> +.Qin(eN)1+2+3+4+5

    map may be helpful here? ;it con%erts numbers in seB into strings<

    >>> eN = '1,2,3,4,5>>> .Qin(ap(tr, eN))1 2 3 4 5

    no' arbitrary obCects may be in seB instead of Cust strings#

    .ind1 index1 r.ind1 rindex+he find and index functions returns the index of the first found occurrence of the gi%en

    subseBuence# )f it is not found, find returns -" but index raises a !alue8rror# rfind and rindex are the

    same as find and index except that they search through the string from right to left ;i#e# they find the

    last occurance<

    >>> = ell, wrl>>> .in(l)

    2>>> '.ine-(l):ll, wrl>>> .rin(l)10>>> ':.rine-(l)ell, wr>>> '.ine-(l):.rine-(l)ll, wr

    ecause Python strings accept negati%e subscripts, index is probably better used in situations

    like the one sho'n because using find instead 'ould yield an incorrect %alue#

    re)l!e

    :eplace 'orks Cust like it sounds# )t returns a copy of the string 'ith all occurrences of the first

     parameter replaced 'ith the second parameter#

    >>> ell, wrl.replace(, T)ellT, wTrl

    r, using %ariable assignment?

    F Wikib k the e te t te tb k lle ti

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programminghttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    25/98

    From Wikibooks, the open-content textbooks collection

    ex)ndt-s

    :eplaces tabs 'ith the apropriate number of spaces# ;default number of spaces per tab 6( this

    can be changed by passing the tab sie as an argument<

    = abce&tabctaprint print len()t = .e-pantab()print tprint len(t)

    abce& abc a

    13abce& abc a1G

     Notice ho' ;although these both look the same< the second string ;t< has a different length

     because each tab is represented by spaces not tab characters#

    +o use a a tab sie of 4 instead of 6?

    = .e-pantab(4)print print len()

    utputs?

    abce& abc a

    13

    s)lit1 s)litlines

    +he s)lit method returns a list of the 'ords in the string# )t can take a separator argument to use

    instead of 'hitespace#

     >>> = ell, wrl

     >>> .plit() 'ell, , wrl >>> .plit(l) 'e, , , wr,

     Note that in neither case is the separator included in the split strings, but empty strings are

    Python Programming

    http://wikibooks.org/http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    26/98

    Python Programming

    ', Ine line, w line, Ye line, Ml%e line, reen line, >>> .plitline()', Ine line, w line, Ye line, Ml%e line, reen line

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    From Wikibooks the open-content textbooks collection

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming/Stringshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Stringshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Strings&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming/Stringshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Stringshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Strings&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Strings&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    27/98

    From Wikibooks, the open content textbooks collection

    &ISTSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    A-out lists in P$t+on

    list in Python is an ordered group of items# )t is a %ery general structure# Hou can ha%e any

    kind of things in a lists, and they dont ha%e to be all of the same type# For instance, you could put

    numbers, letters, strings and donkeys all on the same list#

    )f you are using a modern %ersion of Python ;and you should beriting lists this 'ay is %ery Buick ;and ob%ious

  • 8/19/2019 Python Prog

    28/98

    Python Programming

    'p, , t, lp, l, lt, p, , t, wp, w, wt, ep,e, et, rp, r, rt

    Pythons list comprehension does not define a scope# ny %ariables that are bound in an

    e%aluation remain bound to 'hate%er they 'ere last bound to 'hen the e%aluation 'as completed?

    >>> print -, yr t

    +his is exactly the same as if the comprehension had been expanded into an explicitly-nested

    group of one or more for statements and 7 or more if statements#

    &ist !retion s+ort!uts

    Python pro%ides a shortcut to initialie a list to a particular sie and 'ith an initial %alue for

    each element?

    >>> Ler='0C5>>> print Ler'0, 0, 0, 0, 0

    +his 'orks for any data type?

    >>> ='C8>>> print ', , , , , , ,

    'ith a ca%eat# >hen building a ne' list by multiplying, Python copies each item by reference#

    +his poses a problem for mutable items, for instance in a multidimensional array 'here eachelement is itself a list# Houd guess that the easy 'ay to generate a t'o dimensional array 'ould be?

    litlit=' '0C4 C5

    and this 'orks, but probably doesnt do 'hat you expect?

    >>> litlit=' '0C4 C5

    >>> print litlit''0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0>>> litlit'0'2=1>>> print litlit''0, 0, 1, 0, '0, 0, 1, 0, '0, 0, 1, 0, '0, 0, 1, 0, '0, 0, 1, 0

    From Wikibooks, the open-content textbooks collection

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programminghttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    29/98

    , p

    >>> litlit=''0C4 r i in ran&e(5)>>> print litlit''0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0>>> litlit'0'2=1

    >>> print litlit''0, 0, 1, 0, '0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0, '0, 0, 0, 0

    O)ertions on lists

    &ist Attri-utes

    ength?

      in the len&th a lit %e the b%ilt in len() eth.  >>> len('1,2,3)  3  >>> a = '1,2,3,4  >>> len( a )  4

    Co#-inin( listsists can be combined in se%eral 'ays# +he easiest is Cust to add them# For instance?

    >>> '1,2 + '3,4'1, 2, 3, 4

    nother 'ay to combine lists is 'ith extend# )f you need to combine lists inside of a lamda,

    extend is the 'ay to go#

    >>> a = '1,2,3>>> b = '4,5,F>>> a.e-ten(b)>>> print a'1, 2, 3, 4, 5, F

    +he other 'ay to append a %alue to a list is to use ))end# For example?

    >>> p='1,2>>> p.appen('3,4)>>> p'1, 2, '3, 4

    Python Programming

    http://wikibooks.org/http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    30/98

    9uch like the slice of a string is a substring, the slice of a list is a list# o'e%er, lists differ

    from strings in that 'e can assign ne' %alues to the items in a list#

    >>> lit'1 = 1G

    >>> lit'2, 1G, V%%rpW, 9.0,WnW

    >e can e%en assign ne' %alues to slices of the lists, 'hich dont e%en ha%e to be the same

    length

    >>> lit'1:4 = 'Spprt%niticU, Sel?U>>> lit

    '2, Vpprt%niticW, Vel?W, VnW

    )ts e%en possible to append things onto the end of lists by assigning to an empty slice?

    >>> lit':0 = '3.14,2.G1>>> lit'3.14, 2.G1, 2, Vpprt%niticW, Vel?W, VnW

    Co#)rin( lists

    ists can be compared for eBuality#

    >>> '1,2 == '1,2r%e>>> '1,2 == '3,4ale

    Sortin( lists

    &orting lists is easy 'ith a sort method#

    >>> lit = '2, 3, 1, a, b>>> lit.rt()>>> lit'1, 2, 3, a, b

     Note that the list is sorted in place, and the sort;< method returns None to emphasie this side

    effect#

    )f you use Python $#4 or higher there are some more sort parameters?

    From Wikibooks, the open-content textbooks collection

    http://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    31/98

    TUP&ESli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    A)o!t t!&les in Python

    tuple in Python is much like a list except that it is immutable ;unchangable< once created#

    +hey are generally used for data 'hich should not be edited#

    Tu)le nottion

    +uples may be created directly or con%erted from lists# Generally, tuples are enclosed in

     parenthesis#

    >>> l = '1, a, 'F, 3.14>>> t = (1, a, 'F, 3.14)>>> t(1, a, 'F, 3.1400000000000001)

    >>> t%ple(l)(1, a, 'F, 3.1400000000000001)>>> t == t%ple(l)r%e>>> t == lale

    lso, tuples 'ill be created from items separated by commas#

     >>> t = $, t%ple, nee, n, paren >>> t ($, t%ple, nee, n, paren)

    one item tuple is created by a item in parens follo'ed by a comma?

     >>> t = ($ in&le ite t%ple,) >>> t

     ($ in&le ite t%ple,)

    P!4in( nd Un)!4in(

    Hou can also perform multiple assignment using tuples#

    Python Programming

    http://en.wikibooks.org/wiki/Python_Programming/Tupleshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Tupleshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Tuples&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Tupleshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Tupleshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Tuples&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    32/98

    ssigning a tuple to a se%eral different %ariables is called Qtuple unpacking,R 'hile assigning

    multiple %alues to a tuple in one %ariable is called Qtuple packing#R >hen unpacking a tuple, or

     performing multiple assignment, you must ha%e the same number of %ariables being assigned to as

    %alues being assigned#

    O)ertions on tu)les

    +hese are the same as for lists except that 'e may not assign to indices or slices, and there is no

    .append. operator#

    >>> a = (1, 2)

    >>> b = (3, 4)>>> a + b(1, 2, 3, 4)>>> a(1, 2)>>> b(3, 4)>>> print a.appen(3)racebac? (t recent call lat):

      ile //, line 1, in A$ttrib%terrr: t%ple bQect ha n attrib%te appen>>> a(1, 2)>>> a'0 = 0racebac? (t recent call lat):  ile //, line 1, in Ayperrr: bQect e nt %pprt ite ai&nent>>> a(1, 2)

    For lists 'e 'ould ha%e had?

    >>> a = '1, 2>>> b = '3, 4>>> a + b'1, 2, 3, 4>>> a

    '1, 2>>> b'3, 4>>> a.appen(3)>>> a'1, 2, 3>>> '0 0

    From Wikibooks, the open-content textbooks collection

    http://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    33/98

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python Programming

    http://en.wikibooks.org/wiki/Python_Programming/Tupleshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Tupleshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Tuples&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Tupleshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Tupleshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Tuples&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Tuples&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    34/98

    DICTIONARIESli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    A)o!t di%tiona$ies in Python

    dictionary in python is a collection of unordered %alues 'hich are accessed by key#

    Di!tionr$ nottion

    Dictionaries may be created directly or con%erted from seBuences# Dictionaries are enclosed in

    curly braces, OP

    >>> = Ocity:"ari, a&e:38, (102,1F50,1F01):$ atri- crinateP>>> eN = '(city,"ari), (a&e, 38), ((102,1F50,1F01),$ atri-crinate)>>> Ocity: "ari, a&e: 38, (102, 1F50, 1F01): $ atri- crinateP

    >>> ict(eN)Ocity: "ari, a&e: 38, (102, 1F50, 1F01): $ atri- crinateP>>> == ict(eN)r%e

    lso, dictionaries can be easily created by ipping t'o seBuences#

    >>> eN1 = (a,b,c,)

    >>> eN2 = '1,2,3,4>>> = ict(Lip(eN1,eN2))>>> Oa: 1, c: 3, b: 2, : 4P

    O)ertions on Di!tionries

    +he operations on dictionaries are some'hat uniBue# &licing is not supported, since the items

    ha%e no intrinsic order#

    >>> = Oa:1,b:2, cat:l%erP>>> .?ey()'a, b, cat>>> .al%e()'1 2 l

    From Wikibooks, the open-content textbooks collection

    http://en.wikibooks.org/wiki/Python_Programming/Dictionarieshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Dictionarieshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Dictionaries&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Dictionarieshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Dictionarieshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Dictionaries&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    35/98

    Co#-inin( two Di!tionries

    Hou can combine t'o dictionaries by using the update method of the primary dictionary# Note

    that the update method 'ill merge existing elements if they conflict#

    >>> = Oapple: 1, ran&e: 3, pear: 2P>>> % = Opear: 4, &rape: 5, len: FP>>> .%pate(%)>>> O&rape: 5, pear: 4, len: F, apple: 1, ran&e: 3P>>>

    Deletin( .ro# di!tionr$el ictinaryZae'ebernae

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python Programming

    http://en.wikibooks.org/wiki/Python_Programming/Dictionarieshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Dictionarieshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Dictionaries&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Dictionarieshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Dictionarieshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Dictionaries&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Dictionaries&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    36/98

    SETSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python also has a implementation of the mathematical set# Unlike seBuence obCects such as lists

    and tuples, in 'hich each element is indexed, a set is an unordered collection of obCects# &ets also

    cannot ha%e duplicate members - a gi%en obCect appears in a set 7 or " times# For more information

    on sets, see the &et +heory 'ikibook#

    Constru!tin( Sets

    ne 'ay to construct sets is by passing any seBuential obCect to the .set. constructor#

    >>> et('0, 1, 2, 3)et('0, 1, 2, 3)>>> et(/bt%e/)et('b, e, , , %, t)

    >e can also add elements to sets one by one, using the .add. function#

    >>> = et('12, 2F, 54)>>> .a(32)>>> et('32, 2F, 12, 54)

     Note that since a set does not contain duplicate elements, if 'e add one of the members of s to s

    again, the add function 'ill ha%e no effect# +his same beha%ior occurs in the .update. function,

    'hich adds a group of elements to a set#

    >>> .%pate('2F, 12, 9, 14)>>> et('32, 9, 12, 14, 54, 2F)

     Note that you can gi%e any type of seBuential structure, or e%en another set, to the update

    function, regardless of 'hat structure 'as used to initialie the set#

    +he set function also pro%ides a copy constructor# o'e%er, remember that the copy

    constructor 'ill copy the set, but not the indi%idual elements#

    >>> 2 = .cpy()

    From Wikibooks, the open-content textbooks collection

    http://en.wikibooks.org/wiki/Python_Programming/Setshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Setshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Sets&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikipedia.org/wiki/sethttp://en.wikibooks.org/wiki/Set_Theoryhttp://en.wikipedia.org/wiki/sethttp://en.wikibooks.org/wiki/Set_Theoryhttp://en.wikibooks.org/wiki/Python_Programming/Setshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Setshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Sets&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    37/98

    >e can also test the membership of entire sets# Gi%en t'o sets S " and S 

    $, 'e check if S 

    " is a

    subset or a superset of S $#

    >>> .i%bet(et('32, 8, 9, 12, 14, 4, 54, 2F, 19))r%e>>> .i%peret(et('9, 12))r%e

     Note that .issubset. and .issuperset. can also accept seBuential data types as arguments

    >>> .i%peret('32, 9)r%e

     Note that the X and J operators also express the issubset and issuperset functions

    respecti%ely#

    >>> et('4, 5, G) = et('9, 12)r%e

    ike lists, tuples, and string, 'e can use the .len. function to find the number of items in a set#

    Re#o"in( Ite#s

    +here are three functions 'hich remo%e indi%idual items from a set, called pop, remo%e, and

    discard# +he first, pop, simply remo%es an item from the set# Note that there is no defined beha%ior

    as to 'hich element it chooses to remo%e#

    >>> = et('1,2,3,4,5,F)>>> .pp()1>>> et('2,3,4,5,F)

    >e also ha%e the .remo%e. function to remo%e a specified element#

    >>> .ree(3)>>> et('2,4,5,F)

    Python Programming

    http://en.wikipedia.org/wiki/Subsethttp://en.wikipedia.org/wiki/Subsethttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    38/98

    >>> et(')

    Itertion O"er Sets>e can also ha%e a loop mo%e o%er each of the items in a set# o'e%er, since sets are

    unordered, it is undefined 'hich order the iteration 'ill follo'#

    >>> = et(/bler&/)>>> r n in :... print n,...

    r b e l &

    Set O)ertions

    Python allo's us to perform all the standard mathematical set operations, using members of

    set# Note that each of these set operations has se%eral forms# ne of these forms, s"#function;s$<

    'ill return another set 'hich is created by .function. applied to S "  and S 

    $# +he other form,

    s"#function@update;s$

  • 8/19/2019 Python Prog

    39/98

    >>> 1 = et('4, F, 9)>>> 2 = et('1, F, 8)>>> 1.yetric@ierence(2)et('8, 1, 4, 9)>>> 1 6 2et('8, 1, 4, 9)>>> 1.yetric@ierence@%pate(2)>>> 1et('8, 1, 4, 9)

    Set Di..eren!e

    Python can also find the set difference of S " and S 

    $, 'hich is the elements that are in S 

    " but not

    in S $#

    >>> 1 = et('4, F, 9)>>> 2 = et('1, F, 8)>>> 1.ierence(2)et('9, 4)>>> 1 2et('9, 4)

    >>> 1.ierence@%pate(2)>>> 1et('9, 4)

    Re.eren!e

    Python ibrary :eference on &et +ypes

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python Programming

    http://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_Complementhttp://python.org/doc/2.4.1/lib/types-set.htmlhttp://en.wikibooks.org/wiki/Python_Programming/Setshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Setshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Sets&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikipedia.org/wiki/Complement_(set_theory)#Relative_Complementhttp://python.org/doc/2.4.1/lib/types-set.htmlhttp://en.wikibooks.org/wiki/Python_Programming/Setshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Setshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Sets&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Sets&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    40/98

    OPERATORSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    1asi%s

    Python math 'orks like you 'ould expect#

    >>> - = 2>>> y = 3

    >>> L = 5>>> - C yF>>> - + y5>>> - C y + L11>>> (- + y) C L25

    Powe$s

    +here is a builtin exponentiation operator II, 'hich can take either integers, floating point or

    complex numbers# +his occupies its proper place in the order of operations#

    Di(ision and Ty&e Con(e$sionDi%iding t'o integers uses integer di%ision, also kno'n as floor di%ision# Using di%ision this

    'ay is deprecated because it is intended to change in the future# )nstead, if you 'ant floor di%ision,

    use //#

    Di%iding by or into a floating point number ;there are no fractional types in Python< 'ill cause

    Python to use true di%ision# +o coerce an integer to become a float, float;

  • 8/19/2019 Python Prog

    41/98

    >>> - = 5>>> -5

    A!g'ented Assign'ent

    +here is shorthand for assigning the output of an operation to one of the inputs?

    >>> - = 2>>> - # 22>>> - C= 3

    >>> - # 2 C 3F>>> - += 4>>> - # 2 C 3 + 410>>> - ;= 5>>> - # (2 C 3 + 4) ; 52>>> - CC= 2

    >>> - # ((2 C 3 + 4) ; 5) CC 24>>> - H= 3>>> - # ((2 C 3 + 4) ; 5) CC 2 H 31

    >>> - = repeat thi >>> - # repeat thirepeat thi

    >>> - C= 3 # ill with - repeate three tie>>> -repeat thi repeat thi repeat thi

    1oolean

    or? if a or b?

    @thi

    else?

    thi

    Python Programming

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    42/98

    5&OW CONTRO&li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    s 'ith most imperati%e languages, there are three main categories of program flo' control?

    • loops

    •  branches

    • function calls

    Function calls are co%ered in a later section#

    Generators might arguably be considered an ad%anced form of program flo' control, but they

    are not co%ered here#

    &oo)s

    )n Python, there are t'o kinds of loops, for loops and 'hile loops#

    5or loo)s

    for loop iterates o%er elements of a seBuence ;tuple or list

  • 8/19/2019 Python Prog

    43/98

    1098GF

    54321

    or 

    r i in ran&e(10,0,2):  print i

    +his 'ill output

    108F4

    2

    or 

    r i in ran&e(10,0,1):  print i,

    +his 'ill output

    10 9 8 G F 5 4 3 2 1

    or 

    r i in ran&e(1,F):  print i

    for loops can ha%e names for each element of a tuple, if it loops o%er a seBuence of tuples# Forinstance

    l = '(1,1), (2,4), (3,9), (4,1F), (5,25)r -,-N%are in l:

    Python Programming

    - = 5

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    44/98

    - 5while - > 0:  print -  - = - 1

    'ill output

    54321

    Pythons 'hile loops can also ha%e an else clause, 'hich is a block of statements that isexecuted ;once< 'hen the statement starts out false# For example?

    - = 5y = -while y > 0:  print y  y = y 1ele:  print -

    this 'ill output

    5432

    15

    Unlike some languages, there is no postcondition loop#

    %re4in(1 !ontinuin( nd t+e else !luse o. loo)s

    Python includes statements to exit a loop ;either a for loop or a 'hile loop< prematurely# +o

    exit a loop, use the break statement

    - = 5while - > 0:  print -

    brea?

    From Wikibooks, the open-content textbooks collection

      print -

    http://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    45/98

    p

    +his 'ill not produce any output#

    +he else clause of loops 'ill be executed if no break statements are met in the loop#

    l = ran&e(1,100)r - in l:  i - == 100:

    print -  brea?ele:  print /100 nt %n in ran&e/

    %rn!+es

    +here is basically only one kind of branch in Python, the if statement# +he simplest form of

    the if statement simple executes a block of code only if a gi%en predicate is true, and skips o%er it if

    the predicate is false

    For instance,

    >>> - = 10>>> i - > 0:... print /"itie/..."itie>>> i - < 0:... print /Ze&atie/

    ...Hou can also add .elif. ;short for .else if.< branches onto the if statement# )f the predicate on

    the first QifR is false, it 'ill test the predicate on the first elif, and run that branch if its true# )f the

    first elif is false, it tries the second one, and so on# Note, ho'e%er, that it 'ill stop checking

     branches as soon as it finds a true predicate, and skip the rest of the if statement# Hou can also end

    your if statements 'ith an .else. branch# )f none of the other branches are executed, then python

    'ill run this branch#

    >>> - = F>>> i - > 0:... print /"itie/... eli - == 0:... print /^er/

    ele:

    Python Programming

    5

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    46/98

    5UNCTIONSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    .!n%tion %alls

    callable object   is an obCect that can accept some arguments ;also called parameters< and

     possibly return an obCect ;often a tuple containing multiple obCects

  • 8/19/2019 Python Prog

    47/98

    , y p p y g g g

    function# )f you do not specify a %alue, then that parameter 'ill ha%e the default %alue gi%en 'hen

    the function executes#

    >>> e iplay@ea&e(ea&e, tr%ncate@ater = 4):... print ea&e':tr%ncate@ater...>>> iplay@ea&e(/ea&e/)e>>> iplay@ea&e(/ea&e/, F)ea&

    Vri-le6&en(t+ Ar(u#ent &ists

    Python allo's you to declare t'o special arguments 'hich allo' you to create arbitrary-lengthargument lists# +his means that each time you call the function, you can specify any number of

    arguments abo%e a certain number#

    e %nctin(irt,ecn,Creainin&):  tateent1  tateent2  ...

    >hen calling the abo%e function, you must pro%ide %alue for each of the first t'o arguments#

    o'e%er, since the third parameter is marked 'ith an asterisk, any actual parameters after the first

    t'o 'ill be packed into a tuple and bound to .remaining#.

    >>> e print@tail(irt,Ctail):... print tail...

    >>> print@tail(1, 5, 2, /e&a/)(5, 2, e&a)

    )f 'e declare a formal parameter prefixed 'ith two  asterisks, then it 'ill be bound to a

    dictionary containing any key'ord arguments in the actual parameters 'hich do not correspond to

    any formal parameters# For example, consider the function?

    e a?e@ictinary(a-@len&th = 10, CCentrie):

      ret%rn ict('(?ey, entrie'?ey) r i, ?ey in en%erate(entrie.?ey()) ii < a-@len&th)

    )f 'e call this function 'ith any key'ord arguments other than max@length, they 'ill be placed

    in the dictionary .entries#. )f 'e include the key'ord argument of max@length, it 'ill be bound to

    the formal parameter max length as usual

    Python Programming

    functions return %alue can be used by assigning it to a %ariable, like so?

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    48/98

    y g g

    - = ()y = bar(5,-)

    2a')da .o$'s

    esides assigning the return %alue of a function to a %ariable, 'e can also create %ariables that

    contain functions# Python pro%ides the QlambdaR key'ord for defining unnamed functions 'hich

    can be assigned to %ariables# Hou place the arguments before the colon, and the return %alue of the

    lambda after# )f this is assigned to a %ariable, you can then use that %ariable as if it 'ere a function

    'ith the same parameters and return %alue as the lambda#

    >>> N%are = laba -: -C->>> N%are(3)9

    Hou can also use %ariables other than the parameters in the lambda# o'e%er, note that the

    lambda function 'ill also use the %alues of %ariables from the scope in 'hich it 'as created, rather

    than the scope in 'hich it is run

    >>> prei- = /Zte: />>> e ret%rn@laba(prei-):... ret%rn laba nte: prei- + nte...>>> prei- = /re: />>> = ret%rn@laba(/$ttn: /)>>> (/arnir% ctpi/)

    $ttn: arnir% ctpi

     Note that all functions in python can be stored to %ariables, and are in fact simply %ariables

    themsel%es#

    >>> a?e@nte = ret%rn@laba>>> a?e@nte(/7ee: /)(/laba calc%l%/)7ee: laba calc%l%

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    From Wikibooks, the open-content textbooks collection

    SCOPING

    http://en.wikibooks.org/wiki/Programming:Python_Scopinghttp://en.wikibooks.org/wiki/Python_Programming/Functionshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Functionshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Functions&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Functions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Functions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Programming:Python_Scopinghttp://en.wikibooks.org/wiki/Python_Programming/Functionshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Functionshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Functions&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Functions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Functions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    49/98

    SCOPINGli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    a$ia)les

    !ariables in Python are automatically declared by assignment# !ariables are al'ays references

    to obCects, and are ne%er typed# ike all lgol-deri%ati%e languages, %ariables exist only in the

    current scope or global scope# >hen they go out of scope, the %ariables are destroyed, but the

    obCects to 'hich they refer are not ;unless the number of references to the obCect drops to ero>> ()15

    >>> bar()

    racebac? (t recent call lat):  ile //, line 1, in tpleel  bar()Zaerrr: nae bar i nt eine

    +he name bar is not found because a higher scope does not ha%e access to the names lo'er in

    the hierarchy#

    )t is a common pitfall to fail to lookup an attribute ;such as a method< of an obCect ;such as acontainer< referenced by a %ariable before the %ariable is assigned the obCect# )n its most common

    form?

    >>> r - in ran&e(10):

    Python Programming

    E'CEPTIONS

    http://en.wikibooks.org/wiki/Python_Programming/Scopinghttp://en.wikibooks.org/wiki/Talk:Python_Programming/Scopinghttp://en.wikibooks.org/w/index.php?title=Python_Programming/Scoping&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Scoping&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Scoping&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Scopinghttp://en.wikibooks.org/wiki/Talk:Python_Programming/Scopinghttp://en.wikibooks.org/w/index.php?title=Python_Programming/Scoping&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Scoping&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Scoping&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    50/98

    E'CEPTIONSli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    Python handles all errors 'ith exceptions#

    n exception is a signal that an error or other unusual condition has occurred# +here are a

    number of built-in exceptions, 'hich indicate conditions like reading past the end of a file, or

    di%iding by ero# Hou can also define your o'n exceptions#

    Risin( ex!e)tions

    >hene%er your program attempts to do something erroneous or meaningless, Python raises

    exception to such conduct?

    >>> 1 ; 0racebac? (t recent call lat):  ile //, line 1, in A^er*iiinrrr: inte&er iiin r %l by Ler

    +his traceback  indicates that the ^er*iiinrrr exception is being raised# +his is a

     built-in exception -- see belo' for a list of all the other ones#

    Ct!+in( ex!e)tions

    )n order to handle errors, you can set up exception handling blocks in your code# +he key'ords

    try and e-cept are used to catch exceptions# >hen an error occurs 'ithin the try block, Pythonlooks for a matching e-cept block to handle it# )f there is one, execution Cumps there#

    )f you execute this code?

    try:  print 1;0e-cept ^er*iiinrrr:

      print /D% cant iie by Ler, y% illy./

    +hen Python 'ill print this?

    D% cant iie by Ler, y% illy.

    From Wikibooks, the open-content textbooks collection

    try:

    http://en.wikibooks.org/wiki/Python_Programming/Exceptionshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Exceptionshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Exceptions&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Exceptionshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Exceptionshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Exceptions&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    51/98

    try:  print (F)e-cept _al%errr:  print /hat al%e wa inali./

    )n this code, the print  statement calls the function # +hat function calls the function &,

    'hich 'ill raise an exception of type !alue8rror# Neither   nor & has a try/e-cept block to

    handle !alue8rror# &o the exception raised propagates out to the main code, 'here there is  an

    exception-handling block 'aiting for it# +his code prints?

    hat al%e wa inali.

    &ometimes it is useful to find out exactly 'hat 'ent 'rong, or to print the python error text

    yourself# For example?

    try:  theile = pen(/the@parrt/)e-cept KIrrr, (rrrZ%ber, rrrJea&e):  i rrrZ%ber == 2: # ile nt %n  print /7rry, the@parrt ha apparently Qine the chir iniible./

      ele:  print /n&rat%latin D% hae ana&e t trip a #/ + tr(rrrZ%ber)+ / errr:/  print rrrJea&e

    >hich of course 'ill print?

    7rry, the@parrt ha apparently Qine the chir iniible.

    Custo# Ex!e)tions

    *ode similar to that seen abo%e can be used to create custom exceptions and pass information

    along 'ith them# +his can be extremely useful 'hen trying to debug complicated proCects# ere is

    ho' that code 'ould look( first creating the custom exception class?

      cla %t-ceptin(-ceptin):

      e @@init@@(el,al%e):  el.paraeter=al%e  e @@tr@@(el):  ret%rn repr(el.paraeter)

    nd then using that exception?

    Python Programming

    Exoti! uses o. ex!e)tions

    http://en.wikibooks.org/wiki/Python_Programminghttp://en.wikibooks.org/wiki/Python_Programming

  • 8/19/2019 Python Prog

    52/98

    8xceptions are good for more than Cust error handling# )f you ha%e a complicated piece of code

    to choose 'hich of se%eral courses of action to take, it can be useful to use exceptions to Cump out

    of the code as soon as the decision can be made# +he Python-based mailing list soft'are 9ailmandoes this in deciding ho' a message should be handled# Using exceptions like this may seem like

    its a sort of G+ -- and indeed it is, but a limited one called an escape continuation#

    *ontinuations are a po'erful functional-programming tool and it can be useful to learn them#

    Sust as a simple example of ho' exceptions make programming easier, say you 'ant to add

    items to a list but you dont 'ant to 'rite clanky if statements to initialie the list( you can do?

      r newKte in newKte:  try:  el.ite.appen(newKte)  e-cept $ttrib%terrr:  el.ite = 'newKte

    +his is also much more efficient then an if statement because it assumes the code 'ill succeed#

    )n fact it 'ill 'ork 33O of the time ?< n if statement 'ould continue to get executed e%en after the

    array has been initialied#

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    From Wikibooks, the open-content textbooks collection

    INPUT AND OUTPUT

    http://en.wikibooks.org/wiki/Python_Programming/Exceptionshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Exceptionshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Exceptions&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Exceptionshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Exceptionshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Exceptions&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Exceptions&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    53/98

    INPUT AND OUTPUTli%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    In&!t

    Python has t'o functions designed for accepting data directly from the user?

    • inp%t() 

    • raw@inp%t() 

    +here are also %ery simple 'ays of reading a file, and for stricter control o%er input, reading

    from stdin is necessary#

    rw7in)ut23

    ra'@input;< asks the user for a string of data ;ended 'ith a ne' line

  • 8/19/2019 Python Prog

    54/98

      try:  - = int(raw@inp%t())  e-cept _al%errr:

      print Knali Z%ber

    is preferable, as input;< uses e%al;< to turn a literal into a python type# +his 'ill allo' a

    malicious person to run arbitary code from inside your program tri%ially#

    5ile In)ut

    5ile O-/e!ts

    Python includes a built-in file type# Files can be opened by using the file types constructor?

    = ile(tet.t-t, r)

    +his means f is open for reading# +he first argument is the filename and the second parameter

    is the mode, 'hich can be r, ', or r', among some others#

    +he most common 'ay to read from a file is simply to iterate o%er the lines of the file?

    = pen(tet.t-t, r)r line in :  print line'0.cle()

    +his 'ill print the first character of each line# Note that a ne'line is attached to the end of eachline read this 'ay#

    )t is also possible to read limited numbers of characters at a time, like so?

    c = .rea(1)while len(c) > 0:  i len(c.trip()) > 0: print c,  c = .rea(1)

    +his 'ill read the characters from f one at a time, and then print them if theyre not 'hitespace#

    file obCect implicitly contains a marker to represent the current position# )f the file marker

    h ld b d b k t th b i i ith l th fil bC t d it C t

    From Wikibooks, the open-content textbooks collection

    iprt y

    http://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    55/98

    For finer control o%er input, use sys#stdin#read;

  • 8/19/2019 Python Prog

    56/98

    r i in ran&e(10):  print i,printr i in ran&e(10,20):  print i,

    'ill output?

    0 1 2 3 4 5 F G 8 910 11 12 13 14 15 1F 1G 18 19

    )f the bare print statement 'ere not present, the abo%e output 'ould look like?

    0 1 2 3 4 5 F G 8 9 10 11 12 13 14 15 1F 1G 18 19

    )f it is not desirable to add spaces bet'een obCects, it is necessary to output only one string, by

    concatenating the string representations of each obCect?

    print tr(1)+tr(2)+tr(0-)+tr(0GGG)+tr(10+5Q)+tr(0.999)+tr(ap)+tr(y)

    'ill output?

    12255511(10+5Q)0.999

    )f you 'ant to a%oid printing the trailing ne'line or space ;space 'hen you use comma at the

    end

  • 8/19/2019 Python Prog

    57/98

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    9odules are a simple 'ay to structure a program# 9ostly, there are modules in the standard

    library and there are other Python files, or directories containing python files, in the current

    directory ;each of 'hich constitute a module

  • 8/19/2019 Python Prog

    58/98

    li%e %ersion A discussion A edit lesson A comment A report an error  A ask a Buestion

    *lasses are a 'ay of aggregating similar data and functions# class is basically a scope inside

    'hich %arious code ;especially function definitions< is executed, and the locals to this scope become

    attributes of the class, and of any obCects constructed by this class# n obCect constructed by a class

    is called an instance of that class#

    De#ining a Class

    +o define a class, use the follo'ing format?

    cla laZae:  ...  ...

    +he capitaliation in this class definition is the con%ention, but is not reBuired by the language#

    Instan%e Const$!%tion

    +he class is a callable obCect that constructs an instance of the class 'hen called# +o construct

    an instance of a class, .call. the class obCect?

    = ()

    +his constructs an instance of class Foo and creates a reference to it in f#

    Class Me')e$s

    )n order to access the member of an instance of a class, use the syntax Xclass

    instanceJ#XmemberJ# )t is also possible to access the members of the class definition 'ith Xclass

    nameJ#XmemberJ#

    Met+ods

    method is a function 'ithin a class +he first argument ;methods must al'ays take at least

    From Wikibooks, the open-content textbooks collection

    In"o4in( Met+ods

    *alling a method is much like calling a function but instead of passing the instance as the first

    http://en.wikibooks.org/wiki/Python_Programming/Classeshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Classeshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Classes&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Classes&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Classes&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://en.wikibooks.org/wiki/Python_Programming/Classeshttp://en.wikibooks.org/wiki/Talk:Python_Programming/Classeshttp://en.wikibooks.org/w/index.php?title=Python_Programming/Classes&action=edithttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Classes&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Talk:Python_Programming/Classes&action=edit&section=newhttp://en.wikibooks.org/w/index.php?title=Python_Programming/Q%26A&action=edit&section=newhttp://wikibooks.org/http://wikibooks.org/

  • 8/19/2019 Python Prog

    59/98

    *alling a method is much like calling a function, but instead of passing the instance as the first

     parameter like the list of formal parameters suggests, use the function as an attribute of the instance#

    >>> .et-(5)>>> .bar()

    +his 'ill output

    5

    )t is possible to call the method on an arbitrary obCect, by using it as an attribute of the definingclass instead of an instance of that class, like so?

    >>> .et-(,5)>>> .bar()

    +his 'ill ha%e the same output#

    D$n#i! Clss Stru!ture

    s sho'n by the method setx abo%e, the members of a Python class can change during runtime,

    not Cust their %alues, unlike classes in languages like * or Sa%a# >e can e%en delete f#x after running

    the code abo%e#

    >>> el .->>> .bar()

    racebac? (t recent call lat):  ile //, line 1, in A  ile //, line 5, in bar$ttrib%terrr: intance ha n attrib%te -

    nother effect of this is that 'e can change the definition of the Foo class during