Sunteți pe pagina 1din 41

Python

Programming
Language


KevinChang
kevin.chang.14159@gmail.com
Github:kevinmc14159
LastupdatedonJuly4,2017
1

Docendodiscimus

byteaching,welearn











ListingofContents
Overview&History
CompiledversusInterpreted
Object-orientedProgramming
General
DataTypes&Variables
Operators
Numbers
Strings
Lists
Tuples
Dictionaries
DecisionMaking
Looping
Functions
Iterators&Generators
Input/Output&Files
Assertions&Exceptions
Classes
Modules
Style

Overview&History
Pythonisageneral-purpose,high-level,interpreted,
object-orientedprogramminglanguage.Pythonwascreatedbythe
DutchprogrammerGuidovanRossumstartinginDecember1989and
firstreleasedin1991.ItisnamedaftertheBritishsketchcomedy
televisionseriesMontyPythonsFlyingCircus.Somenotablefeaturesof
Pythonincludeitseaseoflearning,itseaseofreading,itsbroadstandard
library,aswellasitsscalability.PythonisTuringcomplete,which
meansthatitcantheoreticallysolveanycomputableproblemaccording
totheChurch-TuringThesis.
Currently,PythonismaintainedbythenonprofitPythonSoftware
Foundation.Pythoncanbedownloadedfromitswebsite:
https://www.python.org

CompiledversusInterpreted
High-levelprogramminglanguagesarecomposedofconstructs
similartohumanlanguagesandareconsequentlyeasiertoworkwith.
Conversely,machinelanguagesconsistofinstructionswhicharerun
directlyonacomputersCPU.Whereashigh-levellanguagesmay
containwordsandlogicfromhumanlanguages,machinelanguages
consistof1sand0s.Sourcecodethatiswritteninhigh-level
languagessuchasPythonmustbetranslatedtomachinelanguagesin
ordertobeexecutedonacomputer.
Thetwomainmethodsoftranslatinghigh-levellanguagesto
machinelanguagesarecompilationandinterpretation.Acompiler
translatessourcecodeintoamachinelanguageexecutable.This
executableisthensharedwithotherswhowishtorunthecode.In
contrast,aninterpreterprocessessourcecodelinebylineandexecutes
itimmediatelywithoutcreatinganexecutablefile.
Theadvantagesofcompiledlanguagesarethattheexecutableis
readytorun,theyareoftenfaster,andthesourcecoderemainsprivate.
Thedisadvantagesofcompiledlanguagesarethattheyarenot
4

cross-platform,arenotveryflexible,andtakeanextracompilationstep.
Theadvantagesofinterpretedlanguagesarethattheyare
cross-platform,simplertotest,andeasiertodebug.Thedisadvantages
ofinterpretedlanguagesarethataninterpreterisrequiredtorunthe
sourcecode,theyareoftenslower,andthesourcecodeispublic.

Object-orientedProgramming
Pythonadherestotheobject-orientedprogrammingparadigm.
Object-orientedprogrammingisbasedontheconceptofobjects
whichcontaindatathatrepresentstate,andfunctionsthatrepresent
behavior.Theparadigmisfoundedupontheideathatwhen
approachingproblems,datatypesaredeterminedfirstandthen
appropriateoperationsareassociatedwiththedatatypes.
Classesaretemplatesforobjectdefinitionsandcontainfieldsand
methods.Fieldsaredatamemberswhilemethodsarefunction
members.Tocreateactualpiecesofdata,instancesofobjectsarecreated
throughaprocesscalledinstantiation.Aclasscanbethoughtofasa
blueprintforcreatingobjects.
Foreachcreatedinstance,theobjecthasitsownfieldsseparate
fromtheclassandotherobjects.However,themethodsdonotneedto
beuniquesothereisonlyonecopyofthemethodsinmemory.
Themainprinciplesofobject-orientedprogrammingareas
follows:
Encapsulation-principlewhereaninstancesfieldsshould
onlybereadbythemethodsofthedefiningclass.External
manipulationisnotallowed.Thisresultsinmodularized
codethatiseasiertofix,modify,anddebug.
Abstraction-principlewhereirrelevantdataaboutanobject
ishiddenandonlyessentialcharacteristicsarevisible.
Abstractionallowsforreducedcomplexityandincreased
efficiencybecauseitallowsotherpeopletousethe
5

functionalityofapieceofcodewithouthavingtoknow
exactlyhowitwasimplemented.
Inheritance-principlewhereadescendantclassinherits
fromanancestorclass,gainingaccesstoallmembersinthe
ancestorclass.Adirectdescendantformsaparent-child
relationship.Inheritancehelpsmodelrealworldobjects.
Polymorphism-principlewhereadescendantclassinherits
fromanancestorclass,butthedescendantclasscanmodify
themembersinheritedforimprovedormoreoptimized
functionality.

General
TorunPythoncodethroughaninteractiveshellafterPythonhas
beeninstalledonamachine,typepythonintheconsole.Toexitthe
PythonInteractiveShell,typeexit().Pythonscriptsendwiththefile
extension.py.TorunaPythonscriptinthecommandline,type
pythonfollowedbythefilename:
$ python hello_world.py
Pythonidentifiersserveasthenamesforvariables,functions,
classes,andotherobjects.Identifiersmuststartwitheitheraletteroran
underscorefollowedbyzeroormoreletters,digits,orunderscores.
Pythondoesnotallowpunctuationcharacterswithinidentifiers.
Reservedwords,ontheotherhand,maynotbeusedasan
identifiername.Reservedwordshavebuilt-inmeaningforthe
programminglanguage.InPython,mostreservedwordsarecomposed
ofonlylowercaseletters.Reservedwordsarecasesensitive.
TableofPythonReservedWords
False None True and

as assert break class

continue def del elif

else except finally for

from global if import


6

in is lambda nonlocal

not or pass raise

return try while with

yield

InPython,anewlinecharacterindicatestheendofastatement.
Insteadofusingcurlybracketstodenoteblocksofcodelikeother
languages,Pythonuseslineindentationprecedingstatementstoformat
codeblocks.Thenumberofspacesintheindentationmaychosenatthe
programmersdiscretion,butallthestatementsinablockofcodemust
beindentedthesamenumberoftimes.
CommentsarestatementsthatarenotexecutedbythePython
interpreter.Theyareusedtohelpotherpeoplereadingthecode
understandit.Pythonsupportssingle-linecomments,butdoesnot
supportmulti-linecomments.Towritesingle-linecomments,entera
hashsign#followedbythecomment.Single-linecommentsmaybe
writtenontheirownlinesoronthesamelineafterastatement.Like
statements,commentsareterminatedbythenewlinecharacter.
Examplesofsingle-linecomments
>>> # This is a comment
>>> x = 10 # This is another comment

DataTypes&Variables
Incomputing,adatatypeisaclassificationofdatawhichtellsthe
compilerorinterpreterhowtheprogrammerintendstousethedata.
Pythonhasfivestandarddatatypes:numbers,strings,lists,tuples,and
dictionaries.Datatypesdeterminewhichoperationsareallowedon
them.
Datamaybeassignedtovariables.Variablesarememorylocations
whichholddata.Thevalueofavariableisassignedusingthe=
assignmentoperator.Duringassignment,thememorylocationdenoted
byavariableidentifierontheleftsideoftheoperatorissettothevalue
7

denotedbythedataontherightsideoftheoperator.Variablesdonot
needtobeexplicitlydeclaredbeforebeingassigned,butdoneedtobe
definedbeforebeingused.
Examplesofvariableassignment
>>> x = 1
>>> y = "Hello"
Pythonalsosupportsmultipleassignment,wheremultiple
variablescanbeassignedvaluesinoneline.Duringmultiple
assignment,variableidentifiersarelistedontheleftsideofthe=
operator,separatedbycommas.Thevaluestobeassignedarelistedon
therightsideoftheoperator,alsoseparatedbycommas.Datais
assignedtoitscorrespondingvariable,meaningthatthefirstpieceof
dataisassignedtothefirstvariable,thesecondpieceofdataisassigned
tothesecondvariable,andsoon.
Exampleofmultipleassignment
>>> x, y = 10, 20 # Same as x = 10 and y = 20
Pythonisadynamicallytypedlanguage.AllPythonobjectsare
typed,butvariableidentifiersarenottyped.Thismeansthatavariable
maybeassignedtoavalueofonetypeandlaterassignedtoavalueofa
differenttype.
Exampleofdynamictyping
>>> x = 10 # x holds a number data type
>>> x = "Hello World" # x now holds a string data type
Theoppositeofassignmentisdereferencing.Duringdereferencing,
thevariableidentifierisremovedasareferencetothedatait
correspondsto.Attemptingtoaccessthevariablewillthenresultinan
error.Dereferencingisdonewiththedelstatement.
Exampleofdereferencing
>>> x = 10
>>> del x # Variable x no longer references 10

Operators
Incomputing,anoperatorisaconstructwhichcanmanipulatethe
valueofdata.Thetypeofapieceofdatadetermineswhichoperations
8

areallowedonit.Pythonsupportsseventypesofoperators:arithmetic,
comparison,assignment,logical,bitwise,membership,andidentity.
TableofArithmeticOperators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo
** Exponentiation
// FloorDivision

Arithmeticoperatorsworkwithnumericdata.TheAddition
operatoraddsthevaluesoftheoperandsoneithersideoftheoperator.
TheSubtractionoperatorsubtractsthevalueoftherightsideoperand
fromthevalueoftheleftsideoperand.TheMultiplicationoperator
multipliesthevaluesoftheoperandsoneithersideoftheoperator.The
Divisionoperatordividesthevalueoftheleftsideoperandbythe
valueoftherightsideoperand.
TheModulooperatordividesthevalueoftheleftsideoperand
bythevalueoftherightsideoperandandreturnstheremainder,called
themodulus.TheExponentiationoperatorraisesthevalueoftheleft
sideoperandtothepowerdenotedbythevalueoftherightside
operand.TheFloorDivisionoperatordividesthevalueoftheleftside
operandbythevalueoftherightsideoperandandroundstheresultto
theclosestintegertowardsnegativeinfinity.
TableofComparisonOperators
== EqualTo
!= NotEqualTo
9

> GreaterThan
< LessThan
>= GreaterThanorEqualTo
<= LessThanorEqualTo

Comparisonoperatorscomparethevaluesoftheoperandson
eithersideoftheoperatorandmakeaconclusionabouttheirrelation.
TheEqualTooperatorcomparesthevaluesofbothoperandsand
returnsTrueiftheyareboththesamevalueorreturnsFalseiftheyare
notthesamevalue.
TheNotEqualTooperatorcomparesthevaluesofbothoperands
andreturnsTrueiftheyarenotthesamevalueorreturnsFalseifthey
areboththesamevalue.
TheGreaterThanoperatorreturnsTrueifthevalueoftheleft
sideoperandisgreaterthanthevalueoftherightsideoperandor
returnsFalseifthevalueoftheleftsideoperandislessthanorequalto
thevalueoftherightsideoperand.
TheLessThanoperatorreturnsTrueifthevalueoftheleftside
operandislessthanthevalueoftherightsideoperandorreturnsFalse
ifthevalueoftheleftsideoperandisgreaterthanorequaltothevalue
oftherightsideoperand.
TheGreaterThanorEqualTooperatorreturnsTrueifthevalue
oftheleftsideoperandisgreaterthanorequaltothevalueoftheright
sideoperandorreturnsFalseifthevalueoftheleftsideoperandisless
thanthevalueoftherightsideoperand.
TheLessThanorEqualTooperatorreturnsTrueifthevalueof
theleftsideoperandislessthanorequaltothevalueoftherightside
operandorreturnsFalseifthevalueoftheleftsideoperandisgreater
thanthevalueoftherightsideoperand.
TableofAssignmentOperators
= Assign
10

+= AddandAssign
-= SubtractandAssign
*= MultiplyandAssign
/= DivideandAssign
%= ModuloandAssign
**= ExponentandAssign
//= FloorDivideandAssign

Theassignmentoperatorsallassignavaluetoavariable.This
variableisalwaystheleftsideoperand.FortheAssignoperator,the
variableisassignedthevalueoftherightsideoperand.Forthe
remainingassignmentoperators,whichinvolveanarithmetic
operation,theexpressionisfirstevaluatedasanarithmeticoperation
usingtheleftsideoperandandtherightsideoperand.Then,theresultof
thearithmeticoperationisassignedtothevariablewhichistheleftside
operand.
TableofLogicalOperators
and LogicalAND
or LogicalOR
not LogicalNOT

LogicaloperatorsperformBooleanalgebrawiththeiroperands.
TheANDlogicaloperatorreturnsTrueifbothoperandsoneitherside
oftheoperatorevaluatetoTrueorreturnsFalseifeitheroneorbothof
theoperandsevaluatestoFalse.
TheORlogicaloperatorreturnsTrueifanoperandoneitherside
oftheoperatorevaluatestoTrueorreturnsFalseifbothoftheoperands
oneithersideoftheoperatorevaluatetoFalse.
11

TheNOTlogicaloperatorreturnsTrueiftheexpressionfollowing
itevaluatestoFalse,orreturnsFalseiftheexpressionfollowingit
evaluatestoTrue.
TableofBitwiseOperators
& BitwiseAND
| BitwiseOR
^ BitwiseXOR
~ BitwiseComplement
<< BitwiseShiftLeft
>> BitwiseShiftRight

Bitwiseoperatorsworkontheindividualbitsthatareusedto
representdata.TheBitwiseANDoperatorperformsabitbybit
comparisonoftwooperandsandreturnstheresultofperforminga
logicalANDoneachpairofcorrespondingbits.
TheBitwiseORoperatorperformsabitbybitcomparisonoftwo
operandsandreturnstheresultofperformingalogicalinclusiveOR
oneachpairofcorrespondingbits.
TheBitwiseXORoperatorperformsabitbybitcomparisonof
twooperandsandreturnstheresultofperformingalogicalexclusive
ORoneachpairofcorrespondingbits.
TheBitwiseComplementoperatorreturnsthecomplementof
theoperand.Foreachbitthatisa1,itisflippedtoa0.Foreachbit
thatisa0,itisflippedtoa1.
TheBitwiseShiftLeftoperatorshiftsallofthebitsoftheleft
operandtowardsthedirectionofthemostsignificantbitbytheamount
indicatedbythevalueoftherightoperand.
TheBitwiseShiftRightoperatorshiftsallofthebitsoftheleft
operandtowardsthedirectionoftheleastsignificantbitbytheamount
indicatedbythevalueoftherightoperand.
12

TableofMembershipOperators
in MemberofSequence
not in NotMemberofSequence

Membershipoperatorstestformembershipinsequences.Thein
operatorreturnsTrueiftheleftsideoperandisanelementoftheright
sideoperand,whichisasequence,andreturnsFalseiftheleftside
operandisnotanelementoftherightsideoperand,whichisa
sequence.
ThenotinoperatorreturnsTrueiftheleftsideoperandisnotan
elementoftherightsideoperand,whichisasequence,andreturns
Falseiftheleftsideoperandisanelementoftherightsideoperand,
whichisasequence.
TableofIdentityOperators
is SameObject
is not NotSameObject
Identityoperatorscomparethememorylocationsofoperands.
Theisoperatorcomparesthememorylocationsofbothoperandsand
returnsTrueifbothoperandspointtothesamelocationinmemoryor
returnsFalseifbothoperandsdonotpointtothesamelocationin
memory.
Theisnotoperatorcomparesthememorylocationsofboth
operandsandreturnsTrueifbothoperandsdonotpointtothesame
locationinmemoryorreturnsFalseifbothoperandspointtothesame
locationinmemory.
ThereisalsoanorderofoperationsinPython,knownasoperator
precedence.WhenthePythoninterpreterreachesanexpression,it
evaluatestheexpressionbasedonoperatorprecedence.Theoperators
withthehigherprecedenceareevaluatedbeforetheoperatorswiththe
lowerprecedence.Iftwooperatorshavethesameprecedence,theyare
evaluatedfromlefttoright.
13

OperatorPrecedence(HighesttoLowest)
** Exponentiation
~ + - Complement,UnaryPlusand
Minus
* / % // Multiply,Divide,Modulo,Floor
Division
+ - Addition,Subtraction
>> << Rightandleftbitwiseshift
& BitwiseAND
^ | BitwiseXORandOR
<= < > >= Comparison
<> == != Equality
= %= /= //= -= += *= **= Assignment
is is not Identity
in not in Membership
not or and Logical

Numbers
NumbersinPythonaresequencesofdigitsthatrepresentquantity.
Numbersstorenumericalvaluesandareimmutable.Numberobjects
arecreatedoncetheirvalueisassignedtoavariableandcanbe
dereferencedusingthedelstatement.Pythonsupportsfourtypesof
numbers:plainintegers,longintegers,floatingpointnumbers,and
complexnumbers.
Integersrepresentpositiveornegativewholenumbersanddonot
containadecimalpoint.Plainintegershaveatleast32bitsofprecision
whereaslongintegershaveunlimitedprecision.Floatingpointnumbers
14

arerealnumberswithadecimalpointbetweentheintegerand
fractionalparts.Complexnumbersareoftheforma+bj,wherea
andbarefloatingpointnumbersandjistheimaginaryunitthat
satisfiestheproperty j 2 =-1.Therealpartofthecomplexnumberisa
whiletheimaginarypartofthecomplexnumberisb.
Examplesofintegers
>>> 1 + 1
2
>>> 2 ** 3
8
Examplesoffloatingpointnumbers
>>> 4 / 3
1.3333333333333333
>>> 3.5 // 2
1.0
Examplesofcomplexnumbers
>>> z = 2 + 3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z * z
(-5+12j)
Furthermore,Pythonalsosupportsconversionofonetypeof
numbertoanother.Numberscanbeconvertedtointegersusingthe
intfunction.Numberscanbeconvertedtofloatingpointnumbers
usingthefloatfunction.Numberscanbeconvertedtocomplex
numbersusingthecomplexfunction.
Examplesofnumberconversion
>>> x = 5.99
>>> int(x)
5
>>> x = 7
>>> float(x)
7.0
>>> x = 2
>>> y = 3
>>> complex(x)
(2+0j)
>>> complex(x, y)
(2+3j)
15

Someusefulnumberfunctionsincludefindingtheabsolutevalue,
ceiling,andfloorofanumber.Theabsolutevalueofanumberisthe
positivedistancebetweenthenumberandzero.Theceilingofanumber
isthesmallestintegernotlessthanthenumber.Thefloorofanumberis
thelargestintegernotgreaterthanthenumber.
Examplesofabsolutevalue,ceiling,andfloor
>>> abs(-5.5)
5.5
>>> import math
>>> math.ceil(-5.5)
-5
>>> math.floor(-5.5)
-6
Anotherusefulfunctionisthepowfunction.Thisfunctioncanbe
usedtoraiseanumbertoacertainpower.
Exampleofraisinganumbertoapower
>>> import math
>>> math.pow(4, 2)
>>> 16.0
Exampleoffindingsquarerootusingpowfunction
>>> import math
>>> math.pow(16, 1/2)
>>> 4.0
Pythoncanalsofindthelargestorsmallestnumberinalistof
numbers.Themaxfunctiontakesasequenceofnumbersandreturns
thenumberwhosevalueisclosesttopositiveinfinity.Themin
functiontakesasequenceofnumbersandreturnsthenumberwhose
valueisclosesttonegativeinfinity.
Exampleoffindingmaxandmin
>>> max(1, -3, 5, -7, 9)
9
>>> min(-2, 4, -6, 8, -10)
-10

Strings
StringsinPythonaresequencesofcharactersthatareenclosedin
single,double,ortriplequotes.Stringsstoretextdataandare
16

immutable.Stringobjectsarecreatedoncetheirvalueisassignedtoa
variableandcanbedereferencedusingthedelstatement.
AllstringsarerepresentedinUnicode.Unlikeotherlanguages,
Pythonhasnocharactertype.Charactersarerepresentedasstringsthat
havealengthof1.Eachcharacterinastringhasanindexvaluewhere
thefirstcharacterstartswiththeindex0,thesecondcharacterhasthe
index1,andsoon.Singlequotesarerepresentedbythesinglequotation
markcharacter;doublequotesarerepresentedbythedoublequotation
markcharacter;triplequotesarerepresentedbyaconsecutivesequence
ofeitherthreesingleorthreedoublequotationmarkcharacters.
Examplesofstrings
>>> 'I am a string.'
'I am a string.'
>>> "So am I."
'So am I.'
>>> """Me
too."""
'Me\ntoo.'
Thelengthofastringissimplythenumberofcharactersthestring
iscomposedof.Whitespaceandpunctuationcharactersarecountedas
charactersinstrings.
Exampleoffindingstringlength
>>> len("Hello World!")
12
Operationsforstringsincludeslice,rangeslice,concatenation,
repetition,andmembership.Thesliceoperatorcanbeusedtoselecta
singlecharacterinastring.Thesliceoperatorworksbyplacingthe
indexpositionofthecharacterbeingaccessedbetweensquarebrackets.
Thesliceoperatorisplacedimmediatelyafterthevariablenameofthe
stringorthestringitself.
Exampleofaccessingviasliceoperator
>>> a = "Hello"
>>> a[1]
'e'
Therangesliceoperatorcanbeusedtoselectmultiplesequential
charactersinastring.Therangesliceoperatorworksbyplacingan
17

indexrangeofcharactersbeingaccessedbetweensquarebrackets.This
rangeisdenotebythestartingindexinclusive,followedbyacolon,
followedbytheendingindexexclusive.Anoptionalthirdargument
indicatesthenumberofindicesincrementedoverbeforethenext
characterisselectedbytheoperator.Therangesliceoperatorisplaced
immediatelyafterthevariablenameofthestringorthestringitself.
Exampleofaccessingviarangesliceoperator
>>> a = "Python"
>>> a[1:5]
'ytho'
>>> "Python"[::2]
'Pto'
Exampleofreversingastringviarangesliceoperator
>>> "Python"[::-1]
'nohtyP'
Stringconcatenationworksbycombiningtwostringsoneither
sideofthe+operatortoformanewstringobject.Therightside
operandisappendedtotheendoftheleftsideoperand.String
concatenationonlyworksifbothoperandsarestringssoanynumbers
mustbeconvertedtostringsbeforebeingconcatenated.
Exampleofstringconcatenation
>>> a = "Hello " # Note the space after the word
>>> b = "World!"
>>> a + b
'Hello World!'
Stringrepetitionworksbyconcatenatingmultiplecopiesofthe
samestringtoformanewstringobjectusingthe*operator.Theleft
sideoperandisthestringtoberepeatedwhiletherightsideoperandis
anintegerthatdetermineshowmanytimesthestringisrepeated.
Exampleofstringrepetition
>>> a = "Hello "
>>> a * 3
'Hello Hello Hello '
Themembershipoperatorsareusedtodetermineifacharacteror
sequenceofcharactersispresentwithinastring.Theinoperator
returnsTrueiftheleftsideoperandisasubstringoftherightside
operandandFalseotherwise.ThenotinoperatorreturnsTrueifthe
18

leftsideoperandisnotasubstringoftherightsideoperandandFalse
otherwise.
Exampleofmembershipoperators
>>> a = "Python"
>>> "yth" in a
True
>>> "yth" not in a
False
Toiterateoverthecharactersthatcomposethestring,aforloop
isused.Duringiteration,thestringisoperatedonasasequenceof
characters.
Exampleofiteratingoverastring
my_string = "Python"
for letter in my_string:
print(letter) # Prints P, y, t, h, o, and n
Therearespecialcharacterswhichcannotberepresented
normallybetweenquotationmarksasastring.Theseincludequotation
marksthemselves,newlines,tabs,andvariousotherspecialcharacters.
Thesespecialcharactersmustberepresentedasescapesequences
throughbackslashnotation.
Exampleofescapecharacter
>>> "Betty\'s flower shop"
"Betty's flower shop"
Whilestringsenclosedinsingleordoublequotescannotspan
acrossmultiplelines,stringsenclosedintriplequotescan.
Exampleoftriplequotestring
>>> """Multi
Line
String"""
'Multi\nLine\nString'
Sincestringsarecomposedofasequenceofcharacters,strings
haveseveralmethodsrelatingtotheircharacters.Theindexmethod
returnstheindexofthefirstoccurrenceofacharacterwhilethecount
methodreturnsthenumberoftimesaparticularcharacterispresentin
thestring.Bothofthesemethodsarecase-sensitive.
Exampleofindexmethod
>>> "Python".index('t')
2
19

Exampleofcountmethod
>>> "Alabama".count('a')
3
Pythonalsosupportstwostringmethodswhichoperateonthe
lettercaseofthecharactersofthestring.Theuppermethod
transformsallofthelettersinthestringtouppercasewhilethelower
methodtransformsallofthelettersinthestringtolowercase.
Exampleofuppermethod
>>> "python".upper()
'PYTHON'
Exampleoflowermethod
>>> "PYTHON".lower()
'python'
Tosplitastringintoalistofsubstrings,usethesplitmethod.The
splitmethodtakesastringargumentwhichservesasthedelimiterto
indicatewhichcharacterorcharactersthestringistobesplitat.
Exampleofsplitmethod
>>> "123a456a789".split("a")
['123', '456', '789']
Toreplaceallinstancesofasubstringinastringwithanother
substring,usethereplacemethod.Thereplacemethodtakes
argumentsforthesubstringtobereplacedandthesubstringthatwill
replace.
Exampleofreplacemethod
>>> "He is. She is.".replace("is", "was")
'He was. She was.'

Lists
InPython,alistisadatatypethatcontainsasequenceofelements.
Theelementsareseparatedbycommasanddonotneedtoallbelongto
thesametype.Theentirelistisenclosedwithsquarebrackets.Unlike
numbersandstrings,listsaremutable,meaningthatindividuallist
elementsmaybeupdatedanddeleted.Listsarecreatedoncetheirvalue
isassignedtoavariableandcanbedereferencedusingthedel
statement.
20

Examplesoflists
>>> list1 = [0, 1, 2, 3, 4]
>>> list2 = ["Python", 100, "x"]
Eachelementinalisthasanindexvalueandthefirstelement
startswiththeindex0,thesecondelementhastheindex1,andsoon.
Likecharactersinstrings,elementsinlistsareaccessedthroughtheslice
operatorandrangesliceoperators.
Exampleofaccessingviasliceoperator
>>> listing = [1, "two", 3, "four"]
>>> listing[1]
'two'
However,elementsinlistscanalsobeupdatedbycombiningthe
sliceoperatororrangesliceoperatorwithanassignmentoperator.
Exampleofupdatingviarangesliceoperator
>>> listing = [1, "two", 5, "four"]
>>> listing[1:3] = [2, 3]
>>> listing
[1, 2, 3, 'four']
Anotherwaytoupdatealistisbyinsertinganelementintothelist
usingtheinsertmethod.Theinsertmethodtakesargumentsforthe
indexthatthenewelementwillbeinsertedtoaswellastheelementto
beinserted.
Exampleoflistinsertion
>>> listing = [1, 2, 3, 4]
>>> listing.insert(0, "Hello")
>>> listing.insert(2, "World")
>>> listing
['Hello', 1, 'World', 2, 3, 4]
Toremoveelementsfromalist,usethedelstatementfollowed
bythesliceoperatorrepresentationoftheelementstoberemovedfrom
thelist.Anotherwaytoremoveanelementfromalististhroughthe
removemethod,whichtakesanargumentoftheelementtobe
removed.
Examplesofelementremoval
>>> listing = [0, 1, 2, 3, 4]
>>> del listing[1:4]
>>> listing
[0, 4]
>>> listing.remove(0)
21

>>> listing
[4]
Therearevariousoperationsthatcanbeperformedonlists.These
includefindinglength,concatenation,repetition,membership,and
iteration.
Exampleoffindinglength
>>> len([1, 2, 3])
3
Exampleoflistconcatenation
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
Exampleoflistrepetition
>>> ["a", "b", "c"] * 2
['a', 'b', 'c', 'a', 'b', 'c']
Exampleoflistmembership
>>> 3 in [0, 1, 2, 3, 4]
True
Exampleoflistiteration
>>> listing = [1, 2, 3, 4]
>>> for x in listing : print(x * 2)

2
4
6
8
InPython,alistcomprehensionisaconcisewaytocreatealist.A
listcomprehensionconsistsofsquarebracketscontaininganexpression
followedbyaforclausefollowedbyzeroormorefororifclauses.
Thenewlycreatedlistwillcontainelementsoftheexpressioninthe
contextoftheforclause.
Exampleoflistcomprehension
>>> [i * 2 for i in range(10) if i % 2 == 0]
[0, 4, 8, 12, 16]

Tuples
InPython,atupleisanimmutabledatatypethatcontainsa
sequenceofelements.Similartolists,theelementsareseparatedby
commasanddonotneedtoallbelongtothesametype.Theentiretuple
22

isoptionallyenclosedwithparentheses.Anylistofcommaseparated
valuesisinterpretedasatuple.
Atuplecomposedofasingleelementmusthaveatrailingcomma
aftertheloneelement.Sincetuplesareimmutable,individualtuple
elementsmaynotbeupdatedordeleted.Tuplesarecreatedoncetheir
valueisassignedtoavariableandcanbedereferencedusingthedel
statement.
Examplesoftuples
>>> tup1 = (0, 1, 2, 3, 4)
>>> tup2 = ("Python", 100, "x")
Eachelementinatuplehasanindexvalueandthefirstelement
startswiththeindex0,thesecondelementhastheindex1,andsoon.
Likecharactersinstringsandelementsinlists,elementsintuplesare
accessedthroughthesliceoperatorandrangesliceoperators.Though
tuplesareimmutable,newtuplescanbecreatedbycombiningportions
ofexistingtuplesthroughconcatenation.
Exampleofaccessingviasliceoperators
>>> tup1 = (1, 2, 3)
>>> tup1[0]
1
>>> tup1[1:3]
(2, 3)
Exampleofcreatinganewtuple
>>> tup1 = (1, 2, 3)
>>> tup2 = ("a", "b", "c")
>>> tup3 = tup1 + tup2
>>> tup3
(1, 2, 3, 'a', 'b', 'c')
Therearevariousoperationsthatcanbeperformedontuples.
Theseincludefindinglength,concatenation,repetition,membership,
anditeration.
Exampleoffindinglength
>>> len((1, 2, 3))
3
Exampleoftupleconcatenation
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
Exampleoftuplerepetition
23

>>> ("a", "b", "c") * 2


('a', 'b', 'c', 'a', 'b', 'c')
Exampleoftuplemembership
>>> 3 in (0, 1, 2, 3, 4)
True
Exampleoftupleiteration
>>> my_tup = (1, 2, 3, 4)
>>> for x in my_tup : print(x * 2)

2
4
6
8

Dictionaries
InPython,adictionaryisadatatypethatcontainsanunordered
setofkey-valuepairs.Eachkeyisseparatedfromitsvaluewithacolon
andeachkey-valuepairisseparatedwithacomma.Theentire
dictionaryisenclosedwithcurlybrackets.Likelists,dictionariesare
mutable,meaningthatindividualkey-valuepairsmaybeupdatedand
deleted.Dictionariesarecreatedoncetheirvalueisassignedtoa
variableandcanbedereferencedusingthedelstatement.
Exampleofadictionary
>>> d = {"Name" : "Kevin", "Age" : "23", "Location" : "USA"}
Thekeysofadictionarymustbeimmutable(number,string,or
tupletype)andunique.Thevaluesofadictionarycanbeofanydata
typeanddonothavetobeunique.Unlikecharactersinstrings,
elementsinlists,andelementsintuples,dictionarykey-valuepairsdo
nothaveanindexassignedtothem.Thisisbecauseadictionaryisnota
sequence.
Thethreemainoperationsondictionariesareaccessing,updating,
anddeleting.Toaccessakeysvalue,usethesliceoperatorwiththekey
astheargument.Toupdateakeysvalue,combinethesliceoperation
withanassignmentoperation.Todeleteakey-valuepair,usethedel
statementwiththesliceoperatorandthekeyastheargument.
Exampleofaccessing,updating,anddeleting
24

>>> my_dict = {"a" : 1, "b" : 2, "c" : 3}


>>> my_dict["a"] # Accessing
1
>>> my_dict["b"] = 99 # Updating
>>> my_dict
{'c': 3, 'a': 1, 'b': 99}
>>> del my_dict["c"] # Deleting
>>> my_dict
{'a': 1, 'b': 99}
Exampleofdictionarylength
>>> my_dict = {"a" : 1, "b" : 2, "c" : 3}
>>> len(my_dict)
3
Examplesofdictionarymembershipviakeys
>>> my_dict = {"a" : 1, "b" : 2, "c" : 3}
>>> "a" in my_dict
True
>>> 1 in my_dict
False
Exampleofdictionaryiterationusingtheitemsmethod,which
returnsalistoftuplesthatconsistofpairsofkeysandvalues.
>>> my_dict = {"a" : 1, "b" : 2, "c" : 3}
>>> for key, value in my_dict.items(): print(key, value)

c 3
a 1
b 2
Exampleofobtainingalistofdictionarykeys
>>> my_dict = {"a" : 1, "b" : 2, "c" : 3}
>>> my_dict.keys()
dict_keys(['a', 'b', 'c'])
Exampleofobtainingalistofdictionaryvalues
>>> my_dict = {"a" : 1, "b" : 2, "c" : 3}
>>> my_dict.values()
dict_values([1, 2, 3])

DecisionMaking
Normally,Pythoncodeisexecutedfromtoptobottomlinebyline
untiltheprogramterminates.However,Pythonallowsforthealteringof
thisflowofexecutionbycheckingforconditionsataspecificmomentof
25

executionoftheprogramandmakingadecisionastowhatcodeshould
beexecutedimmediatelyafterwardsbasedonthoseconditions.
Pythonimplementsdecisionmakingthroughtheifstatement.
Theifstatementiscomposedofaheaderandasuite.Theheader
containstheifreservedwordfollowedbyaconditionfollowedbya
colon.Afterthecolonisthesuite,orblockofstatements.Thecondition
isabooleanexpressionthatevaluatestoeitherTrueorFalse.Ifthe
expressionisTrue,thenthestatementsinthesuiteareexecuted.Ifthe
expressionisFalse,thenthestatementsinthesuitearenotexecutedand
theinterpretercontinuesexecutionatthelineimmediatelyafterthe
suite.InPython,anynon-zeroandnon-nullvaluesareTruewhileany
zeroornullvaluesareFalse.
Exampleofifstatement
x = 1
if (x == 1):
print("x is 1") # Prints since x == 1
Inadditiontocodethatexecutesiftheconditionalexpression
evaluatestoTrue,Pythonoptionallyallowsforcodetobeexecutedifthe
conditionalexpressionevaluatestoFalse.Thiscanbeachievedusingan
if...elsestatement,whichcontainsifandelseclauses.Eachclause
containsasuite.Therecanonlybeexactlyoneifclauseandexactly
oneelseclauseperif...elsestatement.Foranif...elsestatement,
eitherthecodeblockintheifclauseisexecutedorthecodeblockin
theelseclauseisexecuted,butneverboth.
Exampleofif...elsestatement
x = 2
if (x == 1):
print("x is 1")
else:
print("x is not 1") # This is printed since x != 1
Asanextensiontohavingconditionalcodeexecuteifacertain
expressionisTrueandadditionalconditionalcodetoexecuteifthe
sameexpressionisFalse,Pythonsupportscheckingagainstmultiple
conditionsthateachhaveaconditionalcodeblocktopotentially
execute.Pythonimplementsthisfunctionalitythroughtheif...elif...else
26

statement.Pythonallowsforzeroormoreelifclausesfollowingtheif
clause.Eachelifclausecontainsanadditionalconditionwitha
correspondingstatementblock.Ifmultipleelifclausesevaluateto
True,onlythesuiteofthefirstelifclausethatevaluatedtoTrueis
executed.Anoptionalelseclausemaybeaddedaftertheelif
clause(s).
Exampleofif...elif...elsestatement
x = 2
if (x == 1):
print("x is 1")
elif (x == 2):
print("x is 2") # This is printed since x == 2
elif (x % 2 == 0):
print("Testing") # Not printed even though True
else:
print("x is not 1 or 2")
Pythonalsosupportsnestedifstatements.Nestedifstatements
areusedtocheckforfurtherconditionsafteraninitialconditionismet.
ThisallowsPythontoexecutecertaincodegivenaspecificcombination
ofconditionsbeingmet.
Exampleofnestedifstatements
x = 11
if ((x % 2) == 0):
if ((x % 3) == 0):
print("x is divisible by 2 and 3")
else:
print("x is divisible by 2")
else:
if ((x % 3) == 0):
print("x is divisible by 3")
else:
print("x is not divisible by 2 or 3") # Printed
Pythonallowsforthecombiningoflogicaloperatorswithdecision
makingtocheckforcombinationsofconditions.
Examplesofcombinationsofconditions
x = 10
if ((x % 2) == 0 and (x % 3) == 0):
print("x is divisible by 6")
else:
print("x is not divisible by 6") # Printed
27

if ((x % 2) == 0 or (x % 3) == 0):
print("x is divisible by 2 or 3") # Printed
else:
print("x is not divisible by 2 or 3")

Looping
Normally,Pythoncodeisexecutedfromtoptobottomlinebyline
untiltheprogramterminates.However,Pythoncanaltertheflowof
executionbyexecutingaspecificblockofcodeseveraltimes
consecutively.Theconstructusedtoexecuteablockofcodemultiple
timesiscalledaloop.Loopscontinuetorepeatedlyexecutea
conditionalcodeblockaslongasaconditionisTrue.Whenthe
conditionbecomesFalse,theinterpreterexitstheloopandcontinues
executionatthelineimmediatelyfollowingtheloopstatementblock.
Pythonusesawhilelooptoexecuteastatementblockan
indeterminatenumberoftimes.Thewhileloopiscomposedofa
headerandsuite.Theheaderiscomposedofthewhilereservedword
followedbyatestexpressionfollowedbyacolon.Aftertheheaderisthe
suite,orloopstatementblock.IfthetestexpressionevaluatestoTrue,
thestatementblockisexecuted.Then,thetestexpressionisevaluated
again.IftheexpressionisstillTrue,theloopcontinuestorepeatuntilthe
expressionbecomesFalse.WhenitisFalse,thentheinterpreterexits
fromtheloop.
Exampleofwhileloop
# Loop prints 0, 1, and 2
x = 0
while (x < 3):
print(x)
x += 1
Pythonusesaforlooptoiterateoversequencessuchasstrings
andlists.Theforloopassignseachelementofthesequenceititerates
overtoatemporaryvariablewhichisdeclaredintheloopheader.The
forloopiscomposedofaheaderandsuite.Theheaderiscomposedof
theforreservedwordfollowedbythetemporaryvariableidentifier
28

followedbytheinreservedwordfollowedbythesequencetoiterate
overfollowedbyacolon.Aftertheheaderisthesuite,orloopstatement
block.Foreachelementinthesequence,theloopstatementblock
executes.Theconditionthattheforloopalwayschecksiswhether
therearemoreelementstoiterateover.Theloopfinisheswhenithas
iteratedovertheentiresequence.
Exampleofforloop
# Loop prints individual letters of a string
for letter in "Python":
print("Current letter: ", letter)
Sometimes,itisusefulforaforlooptoiterateoverasequenceof
consecutivenumbers.Thissequencecanbegeneratedusingtherange
function.Therangefunctionreturnsaclassofimmutableiterable
objectsthatcanbeusedbytheforloop.Whenthefunctiontakesa
positiveintegerargument,itreturnsobjectsthatformasequenceof
integersfrom0inclusiveuntiltheargumentexclusivewithadifference
of1betweeneachobject.
Exampleofrangefunction
for x in range(4):
print(x) # Prints 0 1 2 3
Pythonsupportsloopcontrolstatementswhichcanchangethe
loopexecutionfromitsnormalpattern.Theloopcontrolstatementsare
thebreakstatement,thecontinuestatement,andthepass
statement.Thebreakstatementterminatestheloopimmediatelyand
transfersexecutiontothefirststatementfollowingtheloop.The
continuestatementcausestheinterpretertoimmediatelyskipover
anysubsequentstatementsintheloopbodyandstartthenextiteration
oftheloop.Thepassstatementisusedwhenastatementisrequired
syntactically,butnocodeisintendedtobeexecuted.
Exampleofloopcontrol
# Skips printing "t", stops after "3", and prints after "o"
for letter in "Python12345":
if (letter == "t"):
continue
print("Current letter: ", letter)
if (letter == "o"):
29

pass
print("This is the pass block")
if (letter == "3"):
break
Pythonalsoallowsnestedloops,whicharesimplyloopsinsideof
otherloops.Anykindofloopmaybenestedwithinanyotherkindof
loop.Anestedloopisexecutedinitsentiretyforeachindividual
iterationoftheouterloop.Thereisnolimittohowmanylevelsof
nestingmaybeused.
Exampleofnestedloop
for i in range(1, 11):
for j in range(1, 11):
print(str(i) * j)

Functions
Afunctionisaunitoforganizedandreusablecodethatperformsa
singleaction.Functionscanbeabstractlythoughtofasaspecificfeature
ofaprogram.Functionsarecomposedofafunctionheaderanda
functionsuite.Thefunctionheaderconsistsofthereservedworddef
followedbythefunctionnamefollowedbyasetofparentheses
followedbyacolon.Anyinputdataforthefunction,knownas
arguments,shouldbeplacedbetweentheparentheses.Theheaderis
followedbythefunctionsuite,orstatementblock.Thestatementsofthe
functionstatementblockshouldallbeindentedthesamenumberof
times.Anoptionalreturnstatementfollowedbyanexpressioncauses
thefunctiontoexitandpassesbacktheevaluatedexpressiontothe
caller.
Functionsmaycontainparameters,whicharevariablesinthe
statementblockofthefunctionsuite.Parametershavealocalscope,
meaningthattheycanonlybeaccessedinsidethefunctiontheyare
definedinwhilevariablesdefinedoutsideoffunctionshaveaglobal
scopeandcanbeaccessedanywhereelseintheprogram.Arguments
arethedatathatarepassedintothefunctionsparameters.Atahigh
30

level,functionscantakeinarguments,performoperationsinsidethe
functionbody,andreturnanexpressionbacktothecaller.
Afterafunctionisdefined,itmustbeseparatelycalledinorderto
beexecuted.Callingafunctionrequiresenteringthenameofthe
functionalongwithpassinginargumentsbetweenparenthesesafterthe
functionname.Ifthefunctiontakesnoarguments,thenasetof
parenthesesmustbeplacedafterthefunctionnametocallit.
Exampleoffunctionwithoutarguments
# Defining the function
def speak():
print("I am speaking")
# Calling the function
speak()
Exampleoffunctionwitharguments
# Defining the function
def add(a, b):
print(a + b)
# Calling the function
add(3, 4)
FunctionsinPythonpassparametersbyreferenceasopposedto
value.Whenaparameterispassedbyvalue,thecallerandcalleehave
twoindependentvariableswiththesamevalue.Shouldthecallee
modifytheparameter,thechangeisnotvisibletothecaller.Whena
parameterispassedbyreference,thecallerandcalleeusethesame
variable.Shouldthecalleemodifytheparameter,thechangeisvisibleto
thecaller.
Exampleofpass-by-reference
def changelist(mylist):
mylist[2] = 99
my_list = [1, 2, 3, 4]
changelist(my_list)
# my_list is now [1, 2, 99, 4]
Upondefinition,functionscantakefourtypesofarguments:
required,keyword,default,andvariablelength.Requiredarguments
areargumentsthatmustbepassedtothefunctioninthecorrectorder.
Additionally,passingtoomanyortoofewrequiredargumentswill
resultinanerror.
31

Exampleofrequiredarguments
# Function definition has 2 arguments
def add(x, y):
return (x + y)
# Function call has 2 arguments
add(3, 4)
Functionscanalsotakekeywordarguments.Keywordarguments
allowthecallertoidentifytheargumentsbyparametername.This
allowsthecallertopassintheargumentsoutoforder.
Exampleofkeywordarguments
# Function definition
def print_info(name, age):
print(name)
print(age)
# Function call with arguments out of order
print_info(age = 23, name = "Kevin")
Functionscanalsotakedefaultarguments.Defaultargumentsare
argumentsthatassumeadefaultvalueifavalueisnotpassedinforthat
argumentduringthefunctioncall.Ifavalueispassedinasanargument,
theargumentalwaystakesthevaluepassedoverthedefaultvalue.
Exampleofdefaultarguments
# Function definition
def custom_add(x, y = 0):
return (x + y)
# Function calls
custom_add(x = 5) # Returns 5
custom_add(3, 5) # Returns 8
Functionscanalsotakeinavariablenumberofarguments.During
afunctionsdefinition,avariableprependedwithanasterisksymbol
canfollowanyrequiredarguments.Thevariableisatuplewhichholds
alladditionalargumentspassed.Iftherearenoadditionalarguments,
thenthetupleisempty.
Exampleofvariablelengtharguments
# Function definition
def printing(x, *y):
print(x)
for var in y:
print(var)
# Function calls
printing(1) # Prints 1
32

printing(1, 2, 3) # Prints 1, 2, 3
Pythonsupportstheuseofanonymousfunctions.Anonymous
functionsdonothaveafunctionnameandarenotdefinedusingthe
defreservedword.Thelambdareservedwordisusedinsteadto
declarethesefunctions.Lambdafunctionscantakeanynumberof
arguments,butreturnjustonevalueintheformofanexpression.
Furthermore,lambdafunctionscannotexecutemultipleexpressions.
Exampleoflambdafunction
# Declaration
sum = lambda x, y: x + y
# Calling
sum(3, 4) # Returns 7

Iterators&Generators
Aniteratorisanobjectthatallowsforthetraversalofallelements
ofacollectionregardlessoftheimplementationofthecollection.To
buildaniterator,calltheiterfunction,passinginthecollectionto
traverseasanargument,andassigntheresulttoavariable.Toiterate
throughthecollectionstartingatthefirstelement,usethevariableasan
argumentwhencallingthenextfunction.
Exampleofaniterator
>>> it = iter([1, 2, 3])
>>> next(it)
1
>>> next(it)
2
>>> next(it)
3
Ageneratorisafunctionthatproducesasequenceofvaluesusing
theyieldstatement.Eachtimetheyieldstatementisexecuted,the
functiongeneratesanewvalue.Generatorsarecalledandassignedtoa
variable;thenextfunctioniscalledwiththevariableasanargument
togeneratevalues.
Exampleofagenerator
# Generator definition
def gen_num(n):
i = 0
33

while (i < n):


yield i
i += 1
# Assign generator to variable
it = gen_num(3)
next(it) # Generates 0
next(it) # Generates 1
next(it) # Generates 2

Input/Output&Files
Pythonhastheabilitytodisplayinformationtotheconsoleand
consumeinformationfromtheconsole.Thefunctionusedtodisplay
informationistheprintfunctionwhilethefunctionusedtoconsume
informationistheinputfunction.Theprintfunctiontakesinan
argumentwhichisprintedtotheconsole.Theinputfunctionis
assignedtoavariableandalsotakesinanargument,whichisprintedto
thescreen.Aftertheargumentisprinted,theconsolewaitsfortheuser
toinputdata.Upontheuserenteringthedata,thedataisassignedtothe
variable.
Exampleofprintandinput
>>> x = input("Enter something: ")
Enter something: 10
>>> print(x)
10
Pythonalsosupportsoutputtingformattedstringsthroughthe%
stringformatoperatorinaprintstatement.Forprintingformatted
strings,theprintfunctiontakesasargumentsthestringtobeprinted
withembeddedformatsymbols,followedbythestringformatoperator,
followedbyatupleofthevaluestobeprintedbyreplacingits
correspondingformatsymbol.
Exampleofprintingformattedstrings
>>> print("My name is %s. I weigh %d lbs." % ("Kevin", 145))
My name is Kevin. I weigh 145 lbs.
Inadditiontointeractionthroughtheconsole,Pythonalsohasthe
abilitytoopenandeditotherfiles.Toaccomplishthis,Pythonusesthe
openfunctionandread,seek,write,andclosemethods.
34

Theopenfunctiontakestwoarguments:thenameofthefileto
openaswellastheaccessmodeforopeningthefile.Accessmodescan
includereading,writing,oracombinationofboth.Avariableisassigned
totheopenfunctionandbecomesaFileobject.TheFileobjectsread
methodisusedtoreaddatafromthefileoncethefileisopenfor
reading.Thereadmethodoptionallytakesanargumentindicatingthe
numberofbytestoberead.Shouldthemethodbecalledwithoutan
argument,theentirefileisread.Whenafileisreadusingtheread
method,itcontinuestoreadwhereveritleftoffifitwaspreviously
beingread.Tochangethelocationofwheretoreadfrominthefile,use
theFileobjectsseekmethod,passinginanintegerargumentofthe
zero-basedbyteindexofwheretoreadnext.
TheFileobjectswritemethodisusedtowritedataintoafile
oncethefilehasopenedforwriting.Themethodtakesastringargument
whichiswrittenintothefilerepresentedbythecallingFileobject.The
closemethodisthecomplementtotheopenfunctionandclosesthe
filerepresentedbythecallingFileobject,preventinganymorereading
orwritingofthefile.
Exampleoffilemanipulation
# Suppose the following is in file "input.txt"
abc
def
ghi

# Suppose in the same directory is this script


f = open("input.txt", "r+")
print(f.read())
f.seek(1)
print("\n")
print(f.read())
f.write("I am writing!")
f.close()

#When the script executes, the console displays


abc
def
ghi

bc
35

def
ghi

# The file "input.txt" now contains


abc
def
ghiI am writing!

Assertions&Exceptions
PythoncanbeusedtoevaluatewhetheraconditionisTrueor
Falsebyusingtheassertstatement.Theassertstatementiscomposed
oftheassertreservedwordfollowedbyaconditiontoevaluatethatis
surroundedbyparentheses.Thestatementdoesnothingifthecondition
isTrue,butwillraiseanexceptioniftheconditionisFalse.Anexception
isaneventwhichoccursduringtheexecutionofaprogramthat
disruptsthenormalflowoftheprogram.Anexceptioncanbethought
ofasanyerrorthatthePythoninterpreterdoesnotknowhowto
handle.Ifexceptionsaretoberesolved,theymustbehandledinthe
program.Ifanexceptionoccursanditisnothandled,thePythonscript
terminatesandquits.
Exampleofassertion
def greater_than_zero(x):
assert(x > 0)
greater_than_zero(5) # Does nothing
greater_than_zero(-5) # AssertionError
Foranycodethatmayraiseanexception,itcanbeplacedwithina
tryblocktobehandled.Thetryblockcanbefollowedbynumerous
exceptclauseswhichwillcontaincodetoexecuteifaspecific
exceptionisraised.Furthermore,eachexceptclausecancontain
multipleexceptionstohandlewithoneblockofcode.Aftertheexcept
clauses,anelseclausecanbeplacedtocontaincodethatdoesnotneed
thetryblocksprotection.Theelseclauseisonlyexecutedifthecode
inthetryblockdidnotraiseanexception.Ifthereiscodethatmustbe
executedregardlessofwhetheranexceptionwasraised,itshouldbe
placedinafinallyclauseafterthetryblock.Ifafinallyclauseis
used,exceptclausesandelseclausescannotbeused.
36

Exampleofhandlingaraisedexception
# Following code prints Divided by 0
try:
print(5/0)
except ZeroDivisionError:
print("Divided by 0")
else:
print("OK")
Exampleofnoexceptionsraised
# Following code prints 5.0 and OK
try:
print(5/1)
except ZeroDivisionError:
print("Divided by 0")
else:
print("OK")
Exampleoffinallyblock:
# Prints message in "finally" block before exception is raised
try:
print(5/0)
finally:
print("This block always gets executed")

Classes
Pythonclassdefinitionsarecomposedofaclassheaderandclass
suite.Theclassheaderiscomposedofthereservedwordclass
followedbytheclassnamefollowedbyacolon.Aftertheclassheaderis
theclasssuite,orthecomponentstatementsoftheclass.Theclasssuite
cancontainfieldassignmentaswellasmethoddefinition.
Fieldassignmentisthesameasanyothervariableassignment.
Methoddefinitionisidenticaltoanyotherfunctiondefinitionexceptall
methoddefinitionstakeinaspecialargumentasthefirstargument.The
specialargumentisavariableidentifierusedtorepresenttheinstanceof
theobjectthatiscallingthemethod.Thisservestodifferentiatewhich
instanceiscallingthemethod.Byconvention,thisvariableisnamed
self.
Thefirstmethodinanyclassisthe__init__specialmethod,
whichiscalledwheneveranewinstanceoftheclassiscreated.Itis
37

knownastheclassconstructororinitializationmethod.The__init__
methodtakesinaselfargumentaswellasanyotherargumentswhich
canbeassignedtoparameters,becominginstancevariables.Instance
variablesaredeclaredusingtheselfvariablenamefollowedbythe.
dotoperatorfollowedbytheinstancevariablenamefollowedbyan
assignmentoperation.Theuseofselfinthiscaseenablesthefield
assignmenttobeaninstancevariableassignment.Ifafieldisassigned
outsideofthe__init__method,theassignmentisforaclassvariable.
Tocreateaninstanceofanobjectofaparticularclass,calltheclass
nameasafunctionwhilepassingintheargumentsofthe__init__
methodandassigntheresulttoavariable.Theselfargumentis
implicitanddoesnotneedtobepassedin,whilethevariableisnowa
memorylocationwhichholdsdataforthatinstance.Accessinginstance
variablesisaccomplishedbyenteringthevariableidentifierofthe
particularinstancefollowedbythe.dotoperatorfollowedbythe
instancevariabletoaccess.Callingmethodsisaccomplishedbyentering
thevariableidentifieroftheparticularinstancefollowedbythe.dot
operatorfollowedbythemethodtobecalledwithanyappropriate
argumentspassedin.
ExampleofPythonclass
class Employee:
# Class variable
emp_count = 0

# Class constructor method


def __init__(self, name, wage):
# Instance variable assignment
self.name = name
self.wage = wage
# Updating class variable
Employee.emp_count += 1

def display_employee(self):
print("Name:", self.name, ", Wage:", self.wage)

# Create instances of Employee class


x = Employee("Noah", 25)
y = Employee("Emma", 35)
38

# Calling methods
x.display_employee() # Prints Name: Noah , Wage: 25
y.display_employee() # Prints Name: Emma , Wage: 35

# Print class variable


print(Employee.emp_count) # Prints 2
Classesmayalsobedefinedthroughinheritancefromaparent
class.Thechildclassisdefinedusingthereservedwordclassfollowed
bythechildclassnamefollowedbyanyparentclassestoinheritfrom
enclosedinparenthesesfollowedbyacolonfollowedbythecomponent
statementsofthechildclass.Uponinheritingfromaparentclass,the
childclassautomaticallyhasaccesstothefieldsandmethodsofthe
parentclass.
Exampleofinheritance
# Parent class definition
class Parent:
def __init__(self):
print("Calling parent constructor")
def parent_method(self):
print("Calling parent method")

# Child class definition


class Child(Parent):
def __init__(self):
print("Calling child constructor")
def child_method(self):
print("Calling child method")

# Create instance of child class and call methods


x = Child() # Prints Calling child constructor
x.child_method() # Prints Calling child method
x.parent_method() # Prints Calling parent method

Modules
ModulesarefilesthatcontainPythoncodeintheformof
attributes,consistingofvariables,functions,andclasses.Byconvention,
modulefilenamesshouldbeshortandcomposedofalllowercaseletters.
Toaccesstheseattributesinaseparatescript,animportstatementis
used.Whenascriptusesanimportstatementfollowedbythenameof
themoduletoimport,accesstothemodulesattributesisgranted.
39

Similartousinganinstanceidentifiertoaccessanobjectsfieldsandcall
anobjectsmethods,themoduleidentifierisusedforaccessingand
callingmoduleattributes.
Exampleofaccessingmoduleattributes
# Following code is in "support.py"
var = 10

def greeting():
print("Hello World!")

# Remaining code is in "test.py"


import support

print(support.var) # Prints 10

support.greeting() # Prints Hello World!

Style
Codeisreadmuchmoreoftenthanitiswritten.Consequently,itis
importanttowritecodethatcanbeeasilyunderstoodbyothers.
Generallyspeaking,consistencyisthemostimportantaspectofcoding
style.ThoughthereistechnicallynocorrectwaytowritePythoncode,
thefollowingrecommendationsadheretogoodprogrammingpractices:
Use4spacesperindentationlevel.
Continuationlinesshouldalignwrappedelementsverticallywith
respecttoaleftcolumn.
Preferspacesovertabsastheindentationmethod.
Limitalllinestoamaximumof79characters.
Whenneeded,linebreakbeforeoperators.
Surroundtop-levelfunctionsandclassdefinitionswithtwoblank
lines.
SourcecodeshoulduseUTF-8characterencoding.
Importsshouldbeplacedatthetopofthefileandonseparate
lines.
Single-quotedanddouble-quotedstringsarefunctionallythe
samesobotharefine,butusageofoneortheothershouldremain
consistent.
40

Triple-quotedstringsshouldusedoublequotecharacters.
Avoidunnecessarywhitespaceimmediatelyinsideparentheses,
brackets,orbraces.
Avoidwhitespaceimmediatelyprecedingtheopenparenthesis
thatstartstheargumentlistofafunctioncall.
Avoidtrailingwhitespace.
Commentsshouldbecompletesentences.
Usein-linecommentssparingly.
Variable,function,andmethodidentifiersshouldusesnake_case.
ClassidentifiersshoulduseCamelCase.
Modulesshoulduseshort,all-lowercasenames,butmayuse
snake_casewhenappropriate.

S-ar putea să vă placă și