Python Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPyth…Description complète
Python Projects for Kids
Descripción: Python for Signal Processing
Python Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPyth…Full description
Descripción: Python Notes for Professionals
Python Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Programming for StartersPython Prog...Descripción completa
Python for Android
Python Notes for ProfessionalsFull description
this script is given to students of physics lectures
Programacion de computadora mediante PythonDescripción completa
Descripción completa
Full description
Mario Essert, Domagoj Ševerdija, Ivan Vazler Digitalni udžbenik Python - osnove - Odjel za matematiku Sveučilišta Josipa Jurja Strossmayera Osijek, 2007. Sadržaj Sadržaj 1 Python interpreter 1...
This work is licensed licensed under a Creative Commons AttributionAttribution-NonCommer NonCommercialcialShareAlike 3.0 Unported License. License .
For more information, visit http://pythonforbioogists.!om "et in #$ "erif an% Source Code Pro
ii
About the author Martin starte% his programming !areer by earning #er %&ring the !o&rse of his #hD in evo&tionary bioogy, an% starte% tea!hing other peope to program soon after. "in!e then he has ta&ght intro%&!tory intro%&!tor y programming to h&n%re%s of bioogists, from &n%ergra%&ates to #'s, an% has maintaine% a phiosophy that programming !o&rses m&st be frien%y, approa!habe, approa!habe, an% pra!ti!a. Martin has ta&ght intro%&!tory programming as part of the (ioinformati!s M"! !o&rse at )%inb&rgh *niversity for the past five years, an% is !&rrenty +e!t&rer in (ioinformati!s.
iii
Preface e!ome to #ython for (ioogists. (efore yo& rea% any f&rther, ma-e s&re that this is the most re!ent version of the boo-. #ython for (ioogists is being !ontin&ay &p%ate% an% improve% to ta-e into a!!o&nt !orre!tions, amen%ments an% !hanges to #ython itsef, so its important that yo& are rea%ing the most &pto%ate version. $his fie is revision n&mber 189. $he n&mber of the most re!ent revision !an aays be fo&n% at: http://pythonforbioogists.!om/in%e.php/version/ 'f the revision n&mber iste% at the *+ is higher than the one in bo%, then this is an o&tof%ate o&tof%ate !opy, an% yo& nee% to %onoa% the atest version from http://pythonforbioogists.!om o& noti!e from the !opyright page that the !ontents of this boo- are i!ense% &n%er a Creative Commons 4ttrib&tion 4ttrib&tion "hare4i-e "hare 4i-e i!ense. $his means that yo&re free to %o hat yo& i-e ith it 5 !opy !opy it, emai it to yo&r frien%s, apaper yo&r ab ith it 5 as ong as yo& -eep the attrib&tion. o& !an aso mo%ify it, as ong as yo& i!ense yo&r mo%ifi!ation &n%er the same terms. $he ony thing that the i!ense %oesnt ao is !ommer!ia &se 5 if yo&% i-e to &se the !ontents of this !o&rse for for !ommer!ia p&rposes, get in to&!h ith me at martin6pythonforbioogists.!om
7appy programming8
iv
Table of Contents About the author » ii Preface » iii
1: Introduction and environment
1
Why have a programming book for biologists? » 1 Why Python? » 2 How to use this book » 5 !ercises an" solutions » # $etting in touch » % &etting up your environment » % 'e!t e"itors » 11 (ea"ing the "ocumentation » 12
2: Printing and manipulating text
13
Why are we so intereste" in working with te!t? » 1) Printing a message to the screen » 1* +uotes are important » 15 ,se comments to annotate your co"e » 1 rror messages an" "ebugging » 1% Printing special characters » 21 &toring strings in variables » 21 'ools for manipulating strings » 2* (ecap » )* !ercises » )&olutions » ).
3: Reading and riting files Why are we so intereste" in working with files? » 52 (ea"ing te!t from a file » 5) /iles0 contents an" file names » 55 ealing with newlines » 5# issing files » -3
Why "o we nee" lists an" loops? » #* 4reating lists an" retrieving elements » #Working with list elements » ## Writing a loop » #. n"entation errors » %2 ,sing a string as a list » %) &plitting a string to make a list » %* terating over lines in a file » %* 6ooping with ranges » %5 (ecap » %# !ercises » %. &olutions » .3
!: %riting our on functions Why "o we want to write our own functions? » . . efining a function » 133 4alling an" improving our function » 13) ncapsulation with functions » 135 /unctions "on7t always have to take an argument » 13 /unctions "on7t always have to return a value » 13% /unctions can be calle" with name" arguments » 13% /unction arguments can have "efaults » 113 'esting functions » 111 (ecap » 11) !ercises » 115 &olutions » 11-
'he importance of patterns in biology » 1*1 o"ules in Python » 1*) (aw strings » 1** &earching for a pattern in a string » 1*5 !tracting the part of the string that matche" » 153 $etting the position of a match » 152 &plitting a string using a regular e!pression » 15) /in"ing multiple matches » 15* (ecap » 155 !ercises » 15# &olutions » 15%
8: 'ictionaries
1&8
&toring paire" "ata » 1-% 4reating a "ictionary » 1#) terating over a "ictionary » 1#. (ecap » 1%2 !ercises » 1%) &olutions » 1%*
9: (iles) programs) and user input
19!
vii
/ile contents an" manipulation » 1.5 8asic file manipulation » 1. eleting files an" fol"ers » 1.% 6isting fol"er contents » 1.% (unning e!ternal programs » 1.. (unning a program » 233 &aving program output » 231 ,ser input makes our programs more fle!ible » 231 nteractive user input » 23) 4omman" line arguments » 23* (ecap » 235 !ercises » 23# &olutions » 23%
1
Chapter 1: 'ntro%&!tion an% environment
1:
Introduction and environment
Why have a programming book for biologists? 'f yo&re rea%ing this boo-, then yo& probaby %ont nee% to be !onvin!e% that programming is be!oming an in!reasingy essentia part of the too -it for bioogists of a types. o& might, hoever, nee% to be !onvin!e% that a boo- i-e this one, %eveope% espe!iay for bioogists, !an %o a better 9ob of tea!hing yo& to program than a generap&rpose intro%&!tory programming boo-. 7ere are a fe of the reason hy ' thin- that is the !ase. 4 bioogyspe!ifi! programming boo- aos &s to &se eampes an% eer!ises that &se bioogi!a probems. $his serves to important p&rposes: firsty, it provi%es motivation an% %emonstrates the types of probems that programming !an hep to sove. )perien!e has shon that beginners ma-e m&!h better progress hen they are motivate% by the tho&ght of ho the programs they rite i ma-e their ife easier8 "e!on%y, by &sing bioogi!a eampes, the !o%e an% eer!ises thro&gho&t the boo- !an form a ibrary of &sef& !o%e snippets, hi!h e !an refer ba!- to hen e ant to sove reaife probems. 'n bioogy, as in a fie%s of programming, the same probems ten% to re!&r time an% time again, so its very &sef& to have this !oe!tion of eampes to a!t as a referen!e 5 something thats not possibe ith a generap&rpose programming boo-. 4 bioogyspe!ifi! programming boo- !an aso !on!entrate on the feat&res of the ang&age that are most &sef& to bioogists. 4 ang&age i-e #ython has many feat&res an% in the !o&rse of earning it e inevitaby have to !on!entrate on some an% miss others o&t. $he set of feat&res hi!h are important to &s in bioogy are sighty %ifferent to those hi!h are most &sef& for generap&rpose programming 5 for eampe, e are m&!h more intereste% in manip&ating tet in!&%ing things i-e D;4 an% protein se<&en!es= than the average programmer. 4so, there are severa feat&res of #ython that o&% not normay be %is!&sse% in an intro%&!tory
2
Chapter 1: 'ntro%&!tion an% environment
programming boo-, b&t hi!h are very &sef& to bioogists for eampe, reg&ar epressions an% s&bpro!esses=. 7aving a bioogyspe!ifi! tetboo- aos &s to in!&%e these feat&res, aong ith epanations of hy they are parti!&ary &sef& to &s. 4 reate% point is that a tetboo- ritten 9&st for bioogists aos &s to intro%&!e feat&res in a ay that aos &s to start riting &sef& programs right aay. e !an %o this by ta-ing into a!!o&nt the sorts of probems that repeate%y !rop &p in bioogy, an% prioritising the feat&res that are best at soving them. $his boo- has been %esigne% so that yo& sho&% be abe to start riting sma b&t &sef& programs &sing ony the toos in the first !o&pe of !hapters.
Why Python? +et me start this se!tion ith the fooing statement: programming ang&ages are overrate%. hat ' mean by that is that peope ho are ne to programming ten% to orry far too m&!h abo&t hat ang&age to earn. $he !hoi!e of programming ang&age %oes matter, of !o&rse, b&t it matters far ess than peope thin- it %oes. $o p&t it another ays, !hoosing the >rong> programming ang&age is very &ni-ey to mean the %ifferen!e beteen fai&re an% s&!!ess hen earning. ?ther fa!tors motivation, having time to %evote to earning, hepf& !oeag&es= are far more important, yet re!eive ess attention. $he reason that peope pa!e so m&!h eight on the :what language shoul" learn?: <&estion is that its a big, obvio&s <&estion, an% its not %iffi!&t to fin% peope ho i give yo& strong opinions on the s&b9e!t. 'ts aso the first big <&estion that beginners have to anser on!e theyve %e!i%e% to earn programming, so it ass&mes a great %ea of importan!e in their min%s. $here are three main reasons hy !hoi!e of programming ang&age is not as important as most peope thin- it is. Firsty, neary everybo%y ho spen%s any signifi!ant amo&nt of time programming as part of their 9ob i event&ay en% &p
3
Chapter 1: 'ntro%&!tion an% environment
&sing m&tipe ang&ages. #arty this is 9&st %on to the simpe !onstraints of vario&s ang&ages 5 if yo& ant to rite a eb appi!ation yo& probaby %o it in Javas!ript, if yo& ant to rite a graphi!a &ser interfa!e yo& probaby &se something i-e Java, an% if yo& ant to rite oeve agorithms yo& probaby &se C. "e!on%y, earning a first programming ang&age gets yo& @0A of the ay toar%s earning a se!on%, thir%, an% fo&rth one. +earning to thin- i-e a programmer in the ay that yo& brea- %on !ompe tas-s into simpe ones is a s-i that !&ts a!ross a ang&ages 5 so if yo& spen% a fe months earning #ython an% then %is!over that yo& reay nee% to rite in C, yo&r time ont have been aste% as yo& be abe to pi!- it &p m&!h <&i!-er. $hir%y, the -in%s of probems that e ant to sove in bioogy are generay amenabe to being sove% in any ang&age, even tho&gh %ifferent programming ang&ages are goo% at %ifferent things. 'n other or%s, as a beginner, yo&r !hoi!e of ang&age is vanishingy &ni-ey to prevent yo& from soving the probems that yo& nee% to sove. 7aving sai% a that, hen earning to program e "o nee% to pi!- a ang&age to or- in, so e might as e pi!- one thats going to ma-e the 9ob easier. #ython is s&!h a ang&age for a n&mber of reasons: •
't has a mosty!onsistent synta, so yo& !an generay earn one ay of %oing things an% then appy it in m&tipe pa!es
•
't has a sensibe set of b&itin ibraries for %oing ots of !ommon tas-s
•
't is %esigne% in s&!h a ay that theres an obvio&s ay of %oing most things
•
'ts one of the most i%ey&se% ang&ages in the or%, an% theres a ot of a%vi!e, %o!&mentation an% t&torias avaiabe on the eb
•
'ts %esigne% in a ay that ets yo& start to rite &sef& programs as soon as possibe
B
Chapter 1: 'ntro%&!tion an% environment •
'ts &se of in%entation, hie annoying to peope ho arent &se% to it, is great for beginners as it enfor!es a !ertain amo&nt of rea%abiity
#ython aso has a !o&pe of points to re!ommen% it to bioogists an% s!ientists spe!ifi!ay: •
'ts i%ey &se% in the s!ientifi! !omm&nity
•
't has a !o&pe of very e%esigne% ibraries for %oing !ompe s!ientifi! !omp&ting atho&gh e ont en!o&nter them in this boo-=
•
't en% itsef e to being integrate% ith other, eisting toos
•
't has feat&res hi!h ma-e it easy to manip&ate strings of !hara!ters for eampe, strings of D;4 bases an% protein amino a!i% resi%&es, hi!h e as bioogists are parti!&ary fon% of=
P*t+on vs, Perl For bioogists, the <&estion :what language shoul" learn: often reay !omes %on to the <&estion :shoul" learn Perl or Python?: , so ets anser it hea% on. #er an% #ython are both perfe!ty goo% ang&ages for soving a i%e variety of bioogi!a probems. 7oever, after etensive eperien!e tea!hing both #er an% #ython to bioogists, 've !ome the !on!&sion that #ython is an easier ang&age to earn by virt&e of being more consistent an% more readable. 4n important thing to &n%erstan% abo&t #er an% #ython is that they are incre"ibly simiar %espite the fa!t that they oo- very %ifferent=, so the point above abo&t earning a se!on% ang&age appies %o&by. Many #ython an% #er feat&res have a onetoone !orrespon%en!e, an% so earning #er after earning #ython i be reativey easy 5 m&!h easier than, for eampe, moving to Java or C.
Chapter 1: 'ntro%&!tion an% environment
How to use this book #rogramming boo-s generay fa into to !ategories referen!etype boo-s, hi!h are %esigne% for oo-ing &p spe!ifi! bits of information, an% t&toriatype boo-s, hi!h are %esigne% to be rea% !overto!over. $his boo- is an eampe of the atter 5 !o%e sampes in ater !hapters often &se materia from previo&s ones, so yo& nee% to ma-e s&re yo& rea% the !hapters in or%er. )er!ises or eampes from one !hapter are sometimes &se% to i&strate the nee% for feat&res that are intro%&!e% in the net. $here are a n&mber of f&n%amenta programming !on!epts that are reevant to materia in m&tipe %ifferent !hapters. 'n this boo-, rather than intro%&!e these !on!epts a in one go, 've trie% to epain them as they be!ome ne!essary. $his res&ts in a ten%en!y for earier !hapters to be onger than ater ones, as they invove the intro%&!tion of more ne !on!epts. 4 !ertain amo&nt of 9argon is ne!essary if e ant to ta- abo&t programs an% programming !on!epts. 've trie% to %efine ea!h ne te!hni!a term at the point here its intro%&!e%, an% then &se it thereafter ith o!!asiona remin%ers of the meaning. Chapters ten% to foo a pre%i!tabe str&!t&re. $hey generay start ith a fe paragraphs o&tining the motivation behin% the feat&res that it i !over 5 hy %o they eist, hat probems %o they ao &s to sove, an% hy are they &sef& in bioogy spe!ifi!ayE $hese are fooe% by the main bo%y of the !hapter in hi!h e %is!&ss the reevant feat&res an% ho to &se them. $he ength of the !hapters varies <&ite a ot 5 sometimes e ant to !over a topi! briefy, other times e nee% more %epth. $his se!tion en%s ith a brief re!ap o&tining hat e have earne%, fooe% by eer!ises an% so&tions more on that topi! beo=. 4 !o&pe of notes on typography: bold t*pe is &se% to emphasie important points an% italics for te!hni!a terms an% fie names. here !o%e is mie% in ith norma tet its ritten in a mono-spaced font like this . ?!!asionay there are
G
Chapter 1: 'ntro%&!tion an% environment
footnotes1 to provi%e a%%itiona information that is interesting to -no b&t not !r&!ia to &n%erstan%ing, or to give in-s to eb pages. )ampe !o%e is highighte% ith a soi% bor%er: Some example code goes here
an% eampe o&tp&t i.e. hat e see on the s!reen hen e r&n the !o%e= is highighte% ith a %otte% bor%er: Some output goes here
?ften e ant to oo- at the !o%e an% the o&tp&t it pro%&!es together. 'n these sit&ations, yo& see a re%bor%ere% !o%e bo!- fooe% imme%iatey by a b&e bor%ere% o&tp&t bo!-. "ometimes its ne!essary to refer in the tet to in%ivi%&a ines of !o%e or o&tp&t, in hi!h !ase 've &se% ine n&mberings on the eft: 1
first line 2 second line 3 third line
?ther bo!-s of tet &s&ay fie !ontents or type% !omman% ines= %ont have any -in% of bor%er an% oo- i-e this: contents of a file
1
+i-e this.
H
Chapter 1: 'ntro%&!tion an% environment
!ercises an" solutions $he fina part of ea!h !hapter is a set of eer!ises an% so&tions. $he n&mber an% !ompeity of eer!ises %iffer greaty beteen !hapters %epen%ing on the nat&re of the materia. 4s a r&e, eary !hapters have a arge n&mber of simpe eer!ises, hie ater !hapters have a sma n&mber of more !ompe ones. Many of the eer!ise probems are ritten in a %eiberatey vag&e manner an% the ea!t %etais of ho the so&tions or- is &p to yo& very m&!h i-e reaife programming8= o& !an aays oo- at the so&tions to see one possibe ay of ta!-ing the probem, b&t there are often m&tipe vai% approa!hes. ' strongy re!ommen% that yo& try ta!-ing the eer!ises yo&rsef before rea%ing the so&tions there reay is no s&bstit&te for pra!ti!a eperien!e hen earning to program. ' aso en!o&rage yo& to a%opt an attit&%e of !&rio&s eperimentation hen or-ing on the eer!ises 5 if yo& fin% yo&rsef on%ering if a parti!&ar variation on a probem is sovabe, or if yo& re!ognie a !oseyreate% probem from yo&r on or-, try soving it8 Contin&o&s eperimentation is a -ey part of %eveoping as a programmer, an% the <&i!-est ay to fin% o&t hat a parti!&ar f&n!tion or feat&re i %o is to try it. $he eampe so&tions to eer!ises are ritten in a %ifferent ay to most programming tetboo-s: rather than simpy present the finishe% so&tion, ' have o&tine% the tho&ght pro!esses invove% in soving the eer!ises an% shon ho the so&tion is b&it &p stepbystep. 7opef&y this approa!h i give yo& an insight into the probemsoving min%set that programming re<&ires. 'ts probaby a goo% i%ea to rea% thro&gh the so&tions even if yo& s&!!essf&y sove the eer!ise probems yo&rsef, as they sometimes s&ggest an approa!h that is not imme%iatey obvio&s.
I
Chapter 1: 'ntro%&!tion an% environment
$etting in touch ?ne of the most !onvin!ing arg&ments for presenting a !o&rse i-e this one in the form of an eboo- is that it !an be !ontin&ay &p%ate% an% tea-e% base% on rea%er fee%ba!-. "o, if yo& fin% anything that is har% to &n%erstan%, or yo& thin- may !ontain an error, pease get in to&!h 5 9&st %rop me an emai at martin6pythonforbioogists.!om an% ' promise to get ba!- to yo&.
&etting up your environment 4 that yo& nee% in or%er to foo the eampes an% eer!ises in this boo- is a stan%ar% #ython instaation an% a tet e%itor. 4 the !o%e in this boo- i r&n on either +in&, Ma! or in%os ma!hines. $he sight %ifferen!es beteen operating systems are epaine% in the tet mosty in !hapter @=. 'f yo& have a !hoi!e of operating systems on hi!h to earn #ython, ' re!ommen% +in&, Ma! ?" an% in%os in that or%er, simpy be!a&se the *;'base% operating systems +in& an% ?"= are more amenabe to programming in genera.
Installing P*t+on $he pro!ess of instaing #ython %epen%s on the type of !omp&ter yo&re r&nning on. 'f yo&re r&nning a mainstream +in& %istrib&tion i-e *b&nt&, #ython is probaby area%y instae%. $o fin% o&t, open a termina an% type python
'f yo& see some o&tp&t aong these ines: Python 2.7.3 (default, Apr 10 2013, 0!13!1"# $%&& '.7.2 on linux2 )ype *help*, *copyright*, *credits* or *license* for more information. +++
@
Chapter 1: 'ntro%&!tion an% environment
$hen yo& are rea%y to go. 'f yo&r +in& instaation %oesnt area%y have #ython instae%, try instaing it ith yo&r pa!-age manager the !omman% i probaby be either sudo apt-get install python or sudo yum install python =. 'f this %oesnt or-, then %onoa% the pa!-age from the #ython %onoa% page 1. $he offi!ia #ython ebsite has instaation instr&!tions for Ma! 2 an% in%os 3 !omp&ters as e these are i-ey to be the most &pto%ate instr&!tions, so foo them !osey.
Running P*t+on programs 4 #ython program is 9&st a norma tet fie that !ontains #ython !o%e. $o r&n it e m&st first open &p a !omman% ine. ?n +in& an% Ma! !omp&ters, the appi!ation to %o this i be !ae% something aong the ines of >termina>. ?n in%os, it is -non as >!omman% prompt>. $o r&n a #ython program, e 9&st type the path to the #ython ee!&tabe fooe% by the name of the fie that !ontains the !o%e e ant to r&n B. ?n a +in& or Ma! ma!hine, the path i be something i-e: usrlocal-inpython
?n in%os, it i be something i-e: c!Python27python
1 2 3 B
http://.python.org/getit/ http://.python.org/getit/ma!/ http://.python.org/getit/in%os/ hen e refer to >a #ython program> in this boo-, e are &s&ay ta-ing abo&t the tet fie that ho%s the !o%e.
10
Chapter 1: 'ntro%&!tion an% environment
$o r&n a #ython program, its generay easiest to be in the same fo%er as it. (y !onvention, #ython programs are given the etension .py, so to r&n a program !ae% test.py, e 9&st type: usrlocal-inpython test.py
$here are a !o&pe of tri!-s that !an be &sef& hen eperimenting ith programs 1. Firsty, yo& !an r&n #ython in an intera!tive or >she>= mo%e by r&nning it itho&t the name of a program fie. $his aos yo& to type in%ivi%&a statements an% see the res&t straight aay. "e!on%y, yo& !an r&n #ython ith the -i option, hi!h i !a&se it to r&n yo&r program an% t+en enter intera!tive mo%e. $his !an be han%y if yo& ant to eamine the state of variabes after yo&r !o%e has r&n.
P*t+on 2 vs, P*t+on 3 4s i <&i!-y be!ome !ear if yo& spen% any amo&nt of time on the offi!ia #ython ebsite, there are to versions of #ython !&rrenty avaiabe. $he #ython or% is, at the time of riting, in the mi%%e of a transition from version 2 to version 3. 4 %is!&ssion of the pros an% !ons of ea!h version is e beyon% the s!ope of this boo-2, b&t heres hat yo& nee% to -no: insta #ython 3 if possibe, b&t if yo& en% &p ith #ython 2, %ont orry 5 a the !o%e eampes in the boo- i or- ith both versions.
1 2
Dont orry if these to options ma-e no sense to yo& right no 5 they i %o so ater on in the boo-, on!e yo&ve earne% hat statements an% variabes a!t&ay are. o& might en!o&nter riting onine that ma-es the 2 to 3 !hangeover seem i-e a big %ea, an% it is 5 b&t ony for eisting, arge pro9e!ts. hen riting !o%e from s!rat!h, as yo& be %oing hen earning, yo&re &ni-ey to r&n into any probems.
11
Chapter 1: 'ntro%&!tion an% environment
'f yo&re going to &se #ython 2, there is 9&st one thing that yo& have to %o in or%er to ma-e some of the !o%e eampes or-: in!&%e this ine at the start of a yo&r programs: from //future// import diision
e ont go into the epanation behin% this ine, e!ept to say that its ne!essary in or%er to !orre!t a sma <&ir- ith the ay that #ython 2 han%es %ivision of n&mbers. Depen%ing on hat version yo& &se, yo& might see sight %ifferen!es beteen the o&tp&t in this boo- an% the o&tp&t yo& get hen yo& r&n the !o%e on yo&r !omp&ter. 've trie% to note these %ifferen!es in the tet here possibe.
'e!t e"itors "in!e a #ython program is 9&st a tet fie, yo& !an !reate an% e%it it ith any tet e%itor of yo&r !hoi!e. ;ote that by a tet e%itor ' don-t mean a or% pro!essor 5 %o not try to e%it #ython programs ith Mi!rosoft or%, +ibre?ffi!e riter, or simiar toos, as they ten% to insert spe!ia formatting mar-s that #ython !annot rea%. hen !hoosing a tet e%itor, there is one feat&re that is essentia1 to have, an% one hi!h is ni!e to have. $he essentia feat&re is something thats &s&ay !ae% tab emulation. $he effe!t of this feat&re at first seems <&ite o%% hen enabe%, it repa!es any tab !hara!ters that yo& type ith an e<&ivaent n&mber of spa!e !hara!ters &s&ay set to fo&r=. $he reason hy this is &sef& is %is!&sse% at ength in !hapter B, b&t heres a brief epanation: #ython is very f&ssy abo&t yo&r &se of tabs an% spa!es, an% &ness yo& are very %is!ipine% hen typing, its easy to en% &p ith a mit&re of tabs an% spa!es in yo&r programs. $his !a&ses very inf&riating probems, be!a&se they oo- the same to yo&, b&t not to #ython8 $ab em&ation
1
?K, so its not stri!ty essentia, b&t yo& i fin% ife m&!h easer if yo& have it.
12
Chapter 1: 'ntro%&!tion an% environment
fies the probem by ma-ing it effe!tivey impossibe for yo& to type a tab !hara!ter. $he feat&re that is ni!e to have is synta! highlighting . $his i appy %ifferent !oo&rs to %ifferent parts of yo&r #ython !o%e, an% !an hep yo& spot errors more easiy. e!ommen%e% tet e%itors are .otepad// for in%os 1, Text%rangler for Ma! ?"2, an% gedit for +in&3, a of hi!h are freey avaiabe. ?n the eb an% esehere yo& may see referen!es to #ython 'D)s. 'D) stan%s for 'ntegrate% Deveopment )nvironment, an% they typi!ay !ombine a tet e%itor ith a !oe!tion of other &sef& programming toos. hie they !an spee% &p %eveopment for eperien!e% programmers, theyre not a goo% i%ea for beginners as they !ompi!ate things, so ' %ont re!ommen% yo& &se them.
(ea"ing the "ocumentation #art of the tea!hing phiosophy that 've &se% in riting this boo- is that its better to intro%&!e a fe &sef& feat&res an% f&n!tions rather than overhem yo& ith a !omprehensive ist. $he best pa!e to go hen yo& %o ant a !ompete ist of the options avaiabe in #ython is the offi!ia %o!&mentation B hi!h, !ompare% to many ang&ages, is very rea%abe.
?pen the first page of a boo- abo&t earning #ython , an% the !han!es are that the first eampes of !o%e yo& see invove numbers. $heres a goo% reason for that: n&mbers are generay simper to or- ith than tet 5 there are not too many things yo& !an %o ith them on!e yo&ve got basi! arithmeti! o&t of the ay= an% so they en% themseves e to eampes that are easy to &n%erstan%. 'ts aso a pretty safe bet that the average person rea%ing a programming boo- is %oing so be!a&se they nee% to %o some n&mber!r&n!hing. "o hat ma-es this boo- %ifferent 5 hy is this first !hapter abo&t tet rather than n&mbersE $he anser is that, as bioogists, e have a parti!&ar interest in %eaing ith tet rather than n&mbers tho&gh of !o&rse, e nee% to earn ho to manip&ate n&mbers too=. "pe!ifi!ay, ere intereste% in parti!&ar types of tet that e !a se;uences < the D;4 an% protein se<&en!es that !onstit&te the %ata that e %ea ith in bioogy. $here are other reasons that e have a greater interest in or-ing ith tet than the average novi!e programmer. 4s s!ientists, the programs that e rite often nee% to or- as part of a pipeine, aongsi%e other programs that have been ritten by other peope. $o %o this, e often nee% to rite !o%e that !an understand the o&tp&t from some other program e !a this parsing = or produce o&tp&t in a format that another program !an operate on. (oth of these tas-s re<&ire manip&ating tet. 've hinte% above that !omp&ters !onsi%er n&mbers an% tet to be %ifferent in some ay. $hats an important i%ea, an% one that e ret&rn to in more %etai ater. For no, ' ant to intro%&!e an important pie!e of 9argon 5 the or% string . "tring is 1
?r in%ee%, any other programming ang&age
1B
Chapter 2: #rinting an% manip&ating tet
the or% e &se to refer to a bit of tet in a !omp&ter program it 9&st means a string of !hara!ters=. From this point on e &se the or% string hen ere ta-ing abo&t !omp&ter !o%e, an% e reserve the or% se;uence for hen ere %is!&ssing bioogi!a se<&en!es i-e D;4 an% protein.
#rinting a message to the s!reen $he first thing ere going to earn is ho to print 1 a message to the s!reen. 7eres a ine of #ython !o%e that i !a&se a frien%y message to be printe%. L&i!remin%er: soi% ines in%i!ate #ython !o%e, %otte% ines in%i!ate o&tp&t. print(*ello orld*#
+ets ta-e a oo- at the vario&s bits of this ine of !o%e, an% give some of them names: $he hoe ine is !ae% a statement .
print is the name of a function= $he f&n!tion tes #ython, in vag&e terms, hat e ant to %o 5 in this !ase, e ant to print some tet. $he f&n!tion name is aays 2 fooe% by parentheses3. $he bits of tet insi%e the parentheses are !ae% the arguments to the f&n!tion. 'n this !ase, e 9&st have one arg&ment ater on e see eampes of f&n!tions that ta-e more than one arg&ment, in hi!h !ase the arg&ments are separate% by !ommas=.
1
2 3
hen e ta- abo&t printing tet insi%e a !omp&ter program, e are not ta-ing abo&t pro%&!ing a %o!&ment on a printer. $he or% >print> is &se% for any o!!asion hen o&r program o&tp&ts some tet 5 in this !ase, the o&tp&t is %ispaye% in yo&r termina. $his is not stri!ty tr&e, b&t its easier to 9&st foo this r&e than orry abo&t the e!eptions. $here are severa %ifferent types of bra!-ets in #ython, so for !arity e i aays refer to parentheses hen e mean these: =, s;uare brackets hen e mean these: N an% curly brackets hen e mean these: OP
1
Chapter 2: #rinting an% manip&ating tet
$he arg&ments te #ython hat e ant to %o more spe!ifi!ay 5 in this !ase, the arg&ment tes #ython ea!ty hat it is e ant to print: a frien%y greeting. 4ss&ming yo&ve fooe% the instr&!tions in !hapter 1 an% set &p yo&r #ython environment, type the ine of !o%e above into yo&r favo&rite tet e%itor, save it, an% r&n it. o& sho&% see a singe ine of o&tp&t i-e this: ello orld
L&otes are important 'n norma riting, e ony s&rro&n% a bit of tet in <&otes hen e ant to sho that they are being sai% by somebo%y. 'n #ython, hoever, strings are ala*s s&rro&n%e% by <&otes. $hat is ho #ython is abe to te the %ifferen!e beteen the instr&!tions i-e the f&n!tion name= an% the %ata the thing e ant to print=. e !an &se either singe or %o&be <&otes for strings 5 #ython i happiy a!!ept either. $he fooing to statements behave ea!ty the same: print(*ello orld*# print(ello orld#
+ets ta-e a oo- at the o&tp&t to prove it 1: ello orld ello orld
o& noti!e that the o&tp&t above %oesnt !ontain <&otes 5 they are part of the !o%e, not part of the string itsef. 'f e do ant to in!&%e <&otes in the o&tp&t, the easiest thing to %o2 is &se the other type of <&otes for s&rro&n%ing the string: 1 2
From this point on, ' ont te yo& to !reate a ne fie, enter the tet, an% r&n the program for ea!h eampe 5 ' i simpy sho yo& the o&tp&t 5 b&t ' en!o&rage yo& to try the eampes yo&rsef. $he aternative is to pa!e a ba!-sash !hara!ter Q= before the <&ote 5 this is !ae% escaping the <&ote an%
$he above !o%e i give the fooing o&tp&t: She said, ello orld e said, *ello orld*
(e !aref& hen riting an% rea%ing !o%e that invoves <&otes 5 yo& have to ma-e s&re that the <&otes at the beginning an% en% of the string mat!h &p.
*se !omments to annotate yo&r !o%e ?!!asionay, e ant to rite some tet in a program that is for h&mans to rea%, rather than for the !omp&ter to ee!&te. e !a this type of ine a comment . $o in!&%e a !omment in yo&r so&r!e !o%e, start the ine ith a hash symbo 1: 4 this is a comment, it ill -e ignored -y the computer print(*&omments are ery useful5*#
o&re going to see a ot of !omments in the so&r!e !o%e eampes in this boo-, an% aso in the so&tions to the eer!ises. Comments are a very &sef& ay to %o!&ment yo&r !o%e, for a n&mber of reasons: •
1
o& !an p&t the epanation of hat a parti!&ar bit of !o%e %oes right net to the !o%e itsef. $his ma-es it m&!h easier to fin% the %o!&mentation for a ine of !o%e that is in the mi%%e of a arge program, itho&t having to sear!h thro&gh a separate %o!&ment.
i prevent #ython from trying to interpret it. $his symbo has many names 5 yo& might -no it as n&mber sign, po&n% sign, o!tothorpe, sharp from m&si!a notation=, !ross, or pigpen.
1H
Chapter 2: #rinting an% manip&ating tet •
•
(e!a&se the !omments are part of the so&r!e !o%e, they !an never get mie% &p or separate%. 'n other or%s, if yo& are oo-ing at the so&r!e !o%e for a parti!&ar program, then yo& a&tomati!ay have the %o!&mentation as e. 'n !ontrast, if yo& -eep the %o!&mentation in a separate fie, it !an easiy be!ome separate% from the !o%e. 7aving the !omments right net to the !o%e a!ts as a remin%er to &p%ate the %o!&mentation henever yo& !hange the !o%e. $he ony thing orse than &n%o!&mente% !o%e is !o%e ith o% %o!&mentation that is no onger a!!&rate8
Dont ma-e the mista-e, by the ay, of thin-ing that !omments are ony &sef& if yo& are panning on shoing yo&r !o%e to somebo%y ese. hen yo& start riting yo&r on !o%e, yo& i be amae% at ho <&i!-y yo& forget the p&rpose of a parti!&ar se!tion or statement. 'f yo& are or-ing on a so&tion to one of the eer!ises in this boo- on Fri%ay afternoon, then !ome ba!- to it on Mon%ay morning, it i probaby ta-e yo& <&ite a hie to pi!- &p here yo& eft off. Comments !an hep ith this probem by giving yo& hints abo&t the p&rpose of !o%e, meaning that yo& spen% ess time trying to &n%erstan% yo&r o% !o%e, th&s spee%ing &p yo&r progress. 4 si%e benefit is that riting a !omment for a bit of !o%e reinfor!es yo&r &n%erstan%ing at the time yo& are %oing it. 4 goo% habit to get into is riting a <&i!- oneine !omment above any ine of !o%e that %oes something interesting: 4 print a friendly greeting print(*ello orld*#
o& see this te!hni<&e &se% a ot in the !o%e eampes in this boo-, an% ' en!o&rage yo& to &se it for yo&r on !o%e as e.
1I
Chapter 2: #rinting an% manip&ating tet
)rror messages an% %eb&gging 't may seem %epressing eary in the boo- to be ta-ing abo&t errors8 7oever, its orth pointing o&t at this eary stage that computer programs almost never or0 correctl* t+e first time. #rogramming ang&ages are not i-e nat&ra ang&ages 5 they have a very stri!t set of r&es, an% if yo& brea- any of them, the !omp&ter i not attempt to g&ess hat yo& inten%e%, b&t instea% i stop r&nning an% present yo& ith an error message. o&re going to be seeing a ot of these error messages in yo&r programming !areer, so ets get &se% to them as soon as possibe.
(orgetting uotes 7eres one possibe error e !an ma-e hen printing a ine of o&tp&t 5 e !an forget to in!&%e the <&otes: print(ello orld#
$his is easiy %one, so ets ta-e a oo- at the o&tp&t e get if e try to r&n the above !o%e 1: 1 2 3 4 5
$he o&tp&t that yo& see might be very sighty %ifferent from this, %epen%ing on a b&n!h of fa!tors i-e yo&r operating system an% the ea!t version of #ython yo& are &sing.
1@
Chapter 2: #rinting an% manip&ating tet
eferring to the ine n&mbers on the eft e !an see that the name of the #ython fie is error.py ine 1= an% that the error o!!&rs on the first ine of the fie ine 2=. #ythons best g&ess at the o!ation of the error is 9&st before the !ose parentheses ine 3=. Depen%ing on the type of error, this !an be rong by <&ite a bit, so %ont rey on it too m&!h8 $he type of error is a SyntaxError ine =, hi!h mean that #ython !ant &n%erstan% the !o%e 5 it brea-s the r&es in some ay in this !ase, the r&e that strings m&st be s&rro&n%e% by <&otation mar-s=. e see %ifferent types of errors ater in this boo-.
pelling mista0es hat happens if e missspe the name of the f&n!tionE: prin(*ello orld*#
e get a %ifferent type of error 5 a NameError – an% the error message is a bit more hepf&: 1 2 3 4 5
6 python error.py )race-ac: (most recent call last#! ile *error.py*, line 1, in ;module+ prin(*ello orld*#
20
Chapter 2: #rinting an% manip&ating tet
$his time, #ython %oesnt try to sho &s here on the ine the error o!!&rre%, it 9&st shos &s the hoe ine ine B=. $he error message tes &s hi!h or% #ython %oesnt &n%erstan% ine =, so in this !ase, its <&ite easy to fi.
plitting a statement over to lines hat if e ant to print some o&tp&t that spans m&tipe inesE For eampe, e ant to print the or% >7eo> on one ine an% then the or% >or%> on the net ine 5 i-e this: ello =orld
e might try p&tting a ne ine in the mi%%e of o&r string i-e this: print(*ello =orld*#
b&t that ont or- an% e get the fooing error message: 1 2 3 4 5
#ython fin%s the error hen it gets to the en% of the first ine of !o%e ine 2 in the o&tp&t=. $he error message ine = is a bit more !rypti! than the others. >6 stan%s for )n% ?f +ine, an% string literal means a string in <&otes. "o to p&t this error message in pain )ngish: : starte" rea"ing a string in ;uotes0 an" got to the en" of the line before came to the closing ;uotation mark: 'f spitting the ine &p %oesnt or-, then ho %o e get the o&tp&t e ant.....E
21
Chapter 2: #rinting an% manip&ating tet
Printing special characters $he reason that the !o%e above %i%nt or- is that #ython got !onf&se% abo&t hether the ne ine as part of the string hi!h is hat e ante%= or part of the source co"e hi!h is ho it as a!t&ay interprete%=. hat e nee% is a ay to in!&%e a ne ine as part of a string, an% &!-iy for &s, #ython has 9&st s&!h a too b&it in. $o in!&%e a ne ine, e rite a ba!-sash fooe% by the etter n 5 #ython -nos that this is a spe!ia !hara!ter an% i interpret it a!!or%ingy. 7eres the !o%e hi!h prints >7eo or%> a!ross to ines: 4 ho to include a ne line in the middle of a string print(*ellonorld*#
;oti!e that theres no nee% for a spa!e before or after the ne ine. $here are a fe other &sef& spe!ia !hara!ters as e, a of hi!h !onsist of a ba!-sash fooe% by a etter. $he ony ones hi!h yo& are i-ey to nee% for the eer!ises in this boo- are the tab !hara!ter \t= an% the carriage return !hara!ter \r=. $he tab !hara!ter !an sometimes be &sef& hen riting a program that i pro%&!e a ot of o&tp&t. $he !arriage ret&rn !hara!ter or-s a bit i-e a ne ine in that it p&ts the !&rsor ba!- to the start of the ine, b&t %oesnt a!t&ay start a ne ine, so yo& !an &se it to overrite o&tp&t 5 this is sometimes &sef& for ong r&nning programs.
&toring strings in variables ?K, eve been paying aro&n% ith the print f&n!tion for a hie ets intro%&!e something ne. e !an ta-e a string an% assign a name to it &sing an e<&as sign 5 e !a this a variable: 4 store a short @
22