the python guide for beginners...1 preface python has become one of the fastest-growing programming...
TRANSCRIPT
ThePythonGuideforBeginnersRenanMoura
2
ThePythonGuideforBeginners1Preface2IntroductiontoPython3InstallingPython34RunningCode5Syntax6Comments7Variables8Types9Typecasting10UserInput11Operators12Conditionals13Lists14Tuples15Sets16Dictionaries17whileLoops18forLoops19Functions20Scope21ListComprehensions22LambdaFunctions23Modules
3
24if__name__=='__main__'25Files26ClassesandObjects27Inheritance28Exceptions29Conclusion
4
1PrefacePythonhasbecomeoneof the fastest-growingprogramming languagesoverthepastfewyears.
Notonlyitiswidelyused,itisalsoanawesomelanguagetotackleifyouwanttogetintotheworldofprogramming.
This Python Guide for Beginners allows you to learn the core of thelanguageinamatterofhoursinsteadofweeks.
The intention of this book is not to be an exhaustive manual oneverythingPythonhastoofferasoneofthemajorlanguagesinmodernprogramming.
Ifocusonwhatyouwillneedtousemostofthetimetosolvemostoftheproblemsasabeginner.
I deeply believe that you should be able to learn the core of anyprogramminglanguageandthengofromtheretodiveintospecificsanddetailsasneeded.
I'm Renan Moura and I write about Software Development onrenanmf.com.
Youcanalsofindmeas@renanmourafon:
Twitter:https://twitter.com/renanmouraf
5
Linkedin:https://www.linkedin.com/in/renanmourafInstagram:https://www.instagram.com/renanmouraf
6
2IntroductiontoPythonPythonwascreatedin1990byGuidoVanRossuminHolland.
One of the objectives of the language was to be accessible to non-programmers.
Pythonwasalsodesignedtobeasecondlanguageforprogrammerstolearnduetoitslowlearningcurveandeaseofuse.
PythonrunsonMac,Linux,Windows,andmanyotherplatforms.
Pythonis:
Interpreted: it can execute at runtime, and changes in a programare instantly perceptible. To be very technical, Python has acompiler. The difference when compared to Java or C++ is howtransparentandautomaticitis.WithPython,wedon'thavetoworryaboutthecompilationstepasit'sdoneinreal-time.Thetradeoffisthatinterpretedlanguagesareusuallyslowerthancompiledones.
SemanticallyDynamic:youdon'thavetospecifytypesforvariablesandthereisnothingthatmakesyoudoit.
Object-Oriented: everything in Python is an object. But you canchoose to write code in an object-oriented, procedural, or evenfunctionalway.
7
Highlevel:youdon'thavetodealwithlow-levelmachinedetails.
Pythonhasbeengrowingalotrecentlypartlybecauseof itsmanyusesinthefollowingareas:
System scripting: it's a great tool to automate everyday repetitivetasks.
Data Analysis: it is a great language to experiment with and hastonsof librariesand tools tohandledata,createmodels,visualizeresults and even deploy solutions. This is used in areas likeFinance,E-commerce,andResearch.
Web Development: frameworks like Django and Flask allow thedevelopmentofwebapplications,API's,andwebsites.
MachineLearning:TensorflowandPytorcharesomeofthelibrariesthatallowscientistsandtheindustrytodevelopanddeployArtificialIntelligence solutions in Image Recognition, Health, Self-drivingcars,andmanyotherfields.
Youcaneasilyorganizeyourcodeinmodulesandreusethemorsharethemwithothers.
Finally, we have to keep in mind that Python had breaking changesbetweenversions2and3.AndsincePython2supportended in2020,thisarticleissolelybasedonPython3.
Solet'sgetstarted.
8
3InstallingPython3If you use a Mac or Linux you already have Python installed. ButWindowsdoesn'tcomewithPythoninstalledbydefault.
YoualsomighthavePython2,andwearegoingtousePython3.SoyoushouldchecktoseeifyouhavePython3first.
Typethefollowinginyourterminal.
python3-V
NoticetheuppercaseV.
If your result is something similar to 'Python3.x.y', for instance,Python3.8.1,thenyouarereadytogo.
Ifnot,followthenextinstructionsaccordingtoyourOperatingSystem.
3.1InstallingPython3onWindows
Gotohttps://www.python.org/downloads/.
Downloadthelatestversion.
Afterthedownload,double-clicktheinstaller.
Onthefirstscreen,checktheboxindicatingto"AddPython3.xtoPATH"andthenclickon"InstallNow".
9
Wait for the installation process to finish until the next screenwith themessage"Setupwassuccessful".
Clickon"Close".
3.2InstallingPython3onMac
InstallXCodefromtheAppStore.
Installthecommandlinetoolsbyrunningthefollowinginyourterminal.
xcode-select--install
I recommend using Homebrew. Go to https://brew.sh/ and follow theinstructionsonthefirstpagetoinstallit.
After installing Homebrew, run the following brew commands to installPython3.
brewupdate
brewinstallpython3
HomebrewalreadyaddsPython3tothePATH,soyoudon'thavetodoanythingelse.
3.3InstallingPython3onLinux
Toinstallusingapt,availableinUbuntuandDebian,enterthefollowing:
sudoaptinstallpython3
10
Toinstallusingyum,availableinRedHatandCentOS,enterthefollowing:
sudoyuminstallpython3
11
4RunningCodeYou can runPython codedirectly in the terminal as commandsor youcansavethecodeinafilewiththe.pyextensionandrunthePythonfile.
4.1Terminal
Running commands directly in the terminal is recommendedwhen youwanttorunsomethingsimple.
Openthecommandlineandtypepython3:
renan@mypc:~$python3
Youshouldseesomethinglikethisinyourterminalindicatingtheversion(inmycase,Python3.6.9), theoperatingsystem(I'musingLinux),andsomebasiccommandstohelpyou.
The>>>tellsusweareinthePythonconsole.
Python3.6.9(default,Nov72019,10:44:02)
[GCC8.3.0]onlinux
Type"help","copyright","credits"or"license"formoreinformation.
>>>
Let's test itby runningour firstprogramtoperformbasicmathandaddtwonumbers.
>>>2+2
12
Theoutputis:
4
ToexitthePythonconsolesimplytypeexit().
>>>exit()
4.2Running.pyfiles
If you have a complex program, with many lines of code, the Pythonconsoleisn'tthebestoption.
Thealternative issimply toopena texteditor, type thecode,andsavethefilewitha.pyextension.
Let's do that, create a file called second_program.py with the followingcontent.
print('SecondProgram')
Theprint()functionprintsamessageonthescreen.
Themessage goes inside the parentheseswith either single quotes ordoublequotes,bothworkthesame.
Toruntheprogram,onyourterminaldothefollowing:
renan@mypc:~$python3second_program.py
13
Theoutputis:
SecondProgram
14
5SyntaxPythonisknownforitscleansyntax.
The language avoids using unnecessary characters to indicate somespecificity.
5.1Semicolons
Pythonmakesnouseofsemicolonstofinishlines.Anewlineisenoughtotelltheinterpreterthatanewcommandisbeginning.
Theprint()functionwilldisplaysomething.
Inthisexample,wehavetwocommandsthatwilldisplaythemessagesinsidethesinglequotes.
print('Firstcommand')
print('Secondcommand')
Output:
Firstcommand
Secondcommand
Thisiswrongduetothesemicolonsintheend:
print('Firstcommand');
print('Secondcommand');
15
5.2Indentation
Manylanguagesusecurly-bracketstodefinescopes.
Python's interpreterusesonly indentation todefinewhenascopeendsandanotheronestarts.
Thismeans youhave to beawareofwhite spacesat the beginningofeachline--theyhavemeaningandmightbreakyourcodeifmisplaced.
Thisdefinitionofafunctionworks:
defmy_function():
print('Firstcommand')
Thisdoesn'tworkbecausetheindentationofthesecondlineismissingandwillthrowanerror:
defmy_function():
print('Firstcommand')
5.3Casesensitivityandvariables
Pythoniscasesensitive.SothevariablesnameandNamearenotthesamethingandstoredifferentvalues.
name='Renan'
16
Name='Moura'
Asyoucouldsee,variablesareeasilycreatedbyjustassigningvaluestothemusingthe=symbol.
Thismeansnamestores'Renan'andNamestores'Moura'.
5.4Comments
Finally,tocommentsomethinginyourcode,usethehashmark#.
Thecommentedpartdoesnotinfluencetheprogramflow.
#thisfunctionprintssomething
defmy_function():
print('Firstcommand')
Thiswasanoverview,minordetailsoneachofthesewillbecomemoreclearinthenextchapterswithexamplesandbroaderexplanations.
17
6CommentsThepurposeofcommentsistoexplainwhatishappeninginthecode.
Comments are written along with your code but do not influence yourprogramflow.
Whenyouworkbyyourself,maybecommentsdon't feel likesomethingyoushouldwrite.Afterall,at themoment,youknow thewhysofeverysinglelineofcode.
Butwhatifnewpeoplecomeonboardyourprojectafterayearandtheprojecthas3modules,eachwith10,000linesofcode?
Thinkaboutpeoplewhodon'tknowathingaboutyourappandwhoaresuddenlyhavingtomaintainit,fixit,oraddnewfeatures.
Remember,thereisnosinglesolutionforagivenproblem.Yourwayofsolvingthingsisyoursandyoursonly.Ifyouask10peopletosolvethesameproblem,theywillcomeupwith10differentsolutions.
Ifyouwantotherstofullyunderstandyourreasoning,goodcodedesignismandatory,butcommentsareanintegralpartofanycodebase.
6.1HowtoWriteCommentsinPython
ThesyntaxofcommentsinPythonisrathereasy:justusethehashmark#symbolinfrontofthetextyouwanttobeacomment.
18
#Thisisacommentanditwon'tinfluencemyprogramflow
Youcanuseacommenttoexplainwhatsomepieceofcodedoes.
#calculatesthesumofanygiventwonumbers
a+b
6.2MultilineComments
Maybe you want to comment on something very complex or describehowsomeprocessworksinyourcode.
Inthesecases,youcanusemultilinecomments.
Todothat,justuseasinglehashmark#foreachline.
#Everythingafterthehashmark#isacomment
#Thisisacommentanditwon'tinfluencemyprogramflow
#Calculatesthecostoftheprojectgivenvariablesaandb
#aisthetimeinmonthsitwilltakeuntiltheprojectisfinished
#bishowmuchmoneyitwillcostpermonth
a+b*10
19
7VariablesInanyprogram,youneedtostoreandmanipulatedatatocreateafloworsomespecificlogic.
That'swhatvariablesarefor.
Youcanhaveavariabletostoreaname,anotheronetostoretheageofaperson,orevenuseamorecomplextypetostoreallofthisatoncelikeadictionary.
7.1CreatingalsoknownasDeclaring
DeclaringavariableisabasicandstraightforwardoperationinPython.
Justpickanameandattributeavaluetoitusethe=symbol.
name='Bob'
age=32
Youcanusetheprint()functiontoshowthevalueofavariable.
print(name)
print(age)
Bob
20
32
NoticethatinPythonthereisnospecialwordtodeclareavariable.
Themomentyouassignavalue,thevariableiscreatedinmemory.
Pythonalsohasdynamictyping,whichmeansyoudon'thavetotell it ifyourvariableisatextoranumber,forinstance.
Theinterpreterinfersthetypingbasedonthevalueassigned.
If you need it, you can also re-declare a variable just by changing itsvalue.
#declaringnameasastring
name='Bob'
#re-declaringnameasanint
name=32
Keep inmymind, though, that this isnot recommendedsincevariablesmusthavemeaningandcontext.
IfIhaveavariablecallednameIdon'texpectittohaveanumberstoredinit.
7.2NamingConvention
Let's continue from the last section when I talked about meaning andcontext.
Don'tuserandomvariablenameslikexory.
21
Sayyouwanttostorethetimeofaparty,justcallitparty_time.
Oh,didyounoticetheunderscore_?
Byconvention, if youwant touseavariablename that iscomposedoftwo or more words, you separate them by underscores. This is calledSnakeCase.
AnotheroptionwouldbeusingCamelCaseasinpartyTime.This isverycommoninother languages,butnottheconvention inPythonasstatedbefore.
Variablesarecasesensitive, soparty_time andParty_time arenot thesame.Also,keepinmindthattheconventiontellsustoalwaysuselowercase.
Remember, use names that you can recall inside your programeasily.Badnamingcancostyoualotoftimeandcauseannoyingbugs.
Insummary,variablenames:
AreCasesensitive:timeandTIMEarenotthesameHavetostartwithanunderscore_oraletter(DONOTstartwithanumber)Are allowed to have only numbers, letters and underscores. Nospecialcharacterslike:#,$,&,@,etc.
This,forinstance,isnotallowed:party#time,10partytime.
22
8TypesTostoredata inPythonyouneedtouseavariable.Andeveryvariablehasitstypedependingonthevalueofthedatastored.
Python has dynamic typing, which means you don't have to explicitlydeclarethetypeofyourvariable--butifyouwantto,youcan.
Lists, Tuples, Sets, and Dictionaries are all data types and havededicated chapters later on with more details, but we'll look at thembrieflyhere.
Thisway Icanshowyou themost importantaspectsandoperationsofeachone in theirownchapterwhilekeeping this chaptermoreconciseandfocusedongivingyouabroadviewofthemaindatatypesinPython.
8.1DeterminingtheType
Firstofall,let'slearnhowtodeterminethedatatype.
Justusethetype() functionandpassthevariableofyourchoiceasanargument,liketheexamplebelow.
print(type(my_variable))
8.2Boolean
23
Thebooleantypeisoneofthemostbasictypesofprogramming.
AbooleantypevariablecanonlyrepresenteitherTrueorFalse.
my_bool=True
print(type(my_bool))
my_bool=bool(1024)
print(type(my_bool))
<class'bool'>
<class'bool'>
8.3Numbers
Therearethreenumerictypes:int,float,andcomplex.
8.3.1Integer
my_int=32
print(type(my_int))
my_int=int(32)
print(type(my_int))
<class'int'>
<class'int'>
8.3.2Float
my_float=32.85
print(type(my_float))
24
my_float=float(32.85)
print(type(my_float))
<class'float'>
<class'float'>
8.3.3Complex
my_complex_number=32+4j
print(type(my_complex_number))
my_complex_number=complex(32+4j)
print(type(my_complex_number))
<class'complex'>
<class'complex'>
8.4String
The text type isoneof themostcommons typesout thereand isoftencalledstringor,inPython,juststr.
my_city="NewYork"
print(type(my_city))
#Singlequoteshaveexactly
#thesameuseasdoublequotes
my_city='NewYork'
print(type(my_city))
#Settingthevariabletypeexplicitly
my_city=str("NewYork")
print(type(my_city))
25
<class'str'>
<class'str'>
<class'str'>
Youcanusethe+operatortoconcatenatestrings.
Concatenationiswhenyouhavetwoormorestringsandyouwanttojointhemintoone.
word1='New'
word2='York'
print(word1+word2)
NewYork
Thestringtypehasmanybuilt-inmethodsthatletusmanipulatethem.Iwilldemonstratehowsomeofthesemethodswork.
Thelen()functionreturnsthelengthofastring.
print(len('NewYork'))
8
Thereplace()method replacesapartof thestringwithanother.Asanexample,let'sreplace'New'for'Old'.
print('NewYork'.replace('New','Old'))
26
OldYork
Theupper()methodwillreturnallcharactersasuppercase.
print('NewYork'.upper())
NEWYORK
The lower() method does the opposite, and returns all characters aslowercase.
print('NewYork'.lower())
newyork
8.5Lists
A list has its items ordered and you can add the same item asmanytimesasyouwant.Animportantdetailisthatlistsaremutable.
Mutabilitymeansyoucanchangealistafteritscreationbyaddingitems,removingthem,orevenjustchangingtheirvalues.TheseoperationswillbedemonstratedlaterinthechapterdedicatedtoLists.
my_list=["bmw","ferrari","maclaren"]
print(type(my_list))
27
my_list=list(("bmw","ferrari","maclaren"))
print(type(my_list))
<class'list'>
<class'list'>
8.6Tuples
Atupleisjustlikealist:ordered,andallowsrepetitionofitems.
Thereisjustonedifference:atupleisimmutable.
Immutabilitymeansyoucan'tchangeatupleafter itscreation.Ifyoutryto add an item or update one, for instance, the Python interpreter willshowyouanerror.IwillshowthattheseerrorsoccurlaterinthechapterdedicatedtoTuples.
my_tuple=("bmw","ferrari","maclaren")
print(type(my_tuple))
my_tuple=tuple(("bmw","ferrari","maclaren"))
print(type(my_tuple))
<class'tuple'>
<class'tuple'>
8.7Sets
Setsdon'tguaranteetheorderoftheitemsandarenotindexed.
Akeypointwhenusingsets:theydon'tallowrepetitionofanitem.
28
my_set={"bmw","ferrari","maclaren"}
print(type(my_set))
my_set=set(("bmw","ferrari","maclaren"))
print(type(my_set))
<class'set'>
<class'set'>
8.8Dictionaries
Adictionarydoesn'tguaranteetheorderoftheelementsandismutable.
Oneimportantcharacteristic indictionariesisthatyoucansetyourownaccesskeysforeachelement.
my_dict={"country":"France","worldcups":2}
print(type(my_dict))
my_dict=dict(country="France",worldcups=2)
print(type(my_dict))
<class'dict'>
<class'dict'>
29
9TypecastingTypecastingallowsyoutoconvertbetweendifferenttypes.
Thiswayyoucanhaveanintturnedintoastr,orafloatturnedintoanint,forinstance.
9.1Explicitconversion
Tocastavariabletoastringjustusethestr()function.
#thisisjustaregularexplicitintialization
my_str=str('32')
print(my_str)
#inttostr
my_str=str(32)
print(my_str)
#floattostr
my_str=str(32.0)
print(my_str)
32
32
32.0
Tocastavariabletoanintegerjustusetheint()function.
#thisisjustaregularexplicitintialization
my_int=int(32)
print(my_int)
#floattoint:roundsdownto3
my_int=int(3.2)
30
print(my_int)
#strtoint
my_int=int('32')
print(my_int)
32
3
32
Tocastavariabletoafloatjustusethefloat()function.
#thisisanexplicitintialization
my_float=float(3.2)
print(my_float)
#inttofloat
my_float=float(32)
print(my_float)
#strtofloat
my_float=float('32')
print(my_float)
3.2
32.0
32.0
WhatIdidbeforeiscalledanexplicittypeconversion.
In some cases you don't need to do the conversion explicitly, sincePythoncandoitbyitself.
9.2Implicitconversion
Theexamplebelowshowsimplicitconversionwhenaddinganintanda
31
float.
Notice thatmy_sum isfloat.Pythonusesfloat toavoiddata losssincetheinttypecannotrepresentthedecimaldigits.
my_int=32
my_float=3.2
my_sum=my_int+my_float
print(my_sum)
print(type(my_sum))
35.2
<class'float'>
On the other hand, in this example, when you add an int and a str,Pythonwillnotbeable tomake the implicitconversion,and theexplicittypeconversionisnecessary.
my_int=32
my_str='32'
#explicitconversionworks
my_sum=my_int+int(my_str)
print(my_sum)
#implicitconversionthrowsanerror
my_sum=my_int+my_str
64
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:unsupportedoperandtype(s)for+:'int'and'str'
32
Thesameerroristhrownwhentryingtoaddfloatandstrtypeswithoutmakinganexplicitconversion.
my_float=3.2
my_str='32'
#explicitconversionworks
my_sum=my_float+float(my_str)
print(my_sum)
#implicitconversionthrowsanerror
my_sum=my_float+my_str
35.2
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:unsupportedoperandtype(s)for+:'float'and'str'
33
10UserInputIf you need to interact with a user when running your program in thecommand line (forexample, toask forapieceof information), youcanusetheinput()function.
country=input("Whatisyourcountry?")#userenters'Brazil'
print(country)
Brazil
Thecapturedvalueisalwaysstring.Justrememberthatyoumightneedtoconvertitusingtypecasting.
age=input("Howoldareyou?")#userenters'29'
print(age)
print(type(age))
age=int(age)
print(type(age))
Theoutputforeachprint()is:
29
<class'str'>
<class'int'>
34
Noticetheage29iscapturedasstringandthenconvertedexplicitlytoint.
35
11OperatorsInaprogramminglanguage,operatorsarespecialsymbolsthatyoucanapplytoyourvariablesandvaluesinordertoperformoperationssuchasarithmetic/mathematicalandcomparison.
Pythonhas lotsofoperators thatyoucanapply toyourvariablesand Iwilldemonstratethemostusedones.
11.1ArithmeticOperators
Arithmeticoperatorsarethemostcommontypeofoperatorsandalsothemostrecognizableones.
Theyallowyoutoperformsimplemathematicaloperations.
Theyare:
+:Addition-:Subtraction*:Multiplication/:Division**:Exponentiation//:FloorDivision,roundsdowntheresultofadivision%:Modulus,givesyoutheremainderofadivision
Let'sseeaprogramthatshowshoweachofthemisused.
36
print('Addition:',5+2)
print('Subtraction:',5-2)
print('Multiplication:',5*2)
print('Division:',5/2)
print('FloorDivision:',5//2)
print('Exponentiation:',5**2)
print('Modulus:',5%2)
Addition:7
Subtraction:3
Multiplication:10
Division:2.5
FloorDivision:2
Exponentiation:25
Modulus:1
11.1.1Concatenation
Concatenationiswhenyouhavetwoormorestringsandyouwanttojointhemintoone.
This isusefulwhenyouhave information inmultiplevariablesandwanttocombinethem.
For instance, in thisnextexample I combine twovariables that containmyfirstnameandmylastnamerespectivelytohavemyfullname.
The+operatorisalsousedtoconcatenate.
first_name='Renan'
last_name='Moura'
37
print(first_name+last_name)
RenanMoura
Since concatenation is applied to strings, to concatenate strings withothertypes,youhavetodoanexplicittypecastusingstr().
Ihavetotypecasttheintvalue30tostringwithstr()toconcatenateitwiththerestofthestring.
age='Ihave'+str(30)+'yearsold'
print(age)
Ihave30yearsold
11.2ComparisonOperators
Usecomparisonoperatorstocomparetwovalues.
TheseoperatorsreturneitherTrueorFalse.
Theyare:
==:Equal!=:Notequal>:Greaterthan<:Lessthan>=:Greaterthanorequalto
38
<=:Lessthanorequalto
Let'sseeaprogramthatshowshoweachofthemisused.
print('Equal:',5==2)
print('Notequal:',5!=2)
print('Greaterthan:',5>2)
print('Lessthan:',5<2)
print('Greaterthanorequalto:',5>=2)
print('Lessthanorequalto:',5<=2)
Equal:False
Notequal:True
Greaterthan:True
Lessthan:False
Greaterthanorequalto:True
Lessthanorequalto:False
11.3AssignmentOperators
As the name implies, these operators are used to assign values tovariables.
x=7inthefirstexampleisadirectassignmentstoringthenumber7inthevariablex.
Theassignmentoperationtakesthevalueontherightandassigns it tothevariableontheleft.
TheotheroperatorsaresimpleshorthandsfortheArithmeticOperators.
39
Inthesecondexamplexstartswith7andx+=2 is justanotherwaytowritex=x+2,whichmeansthepreviousvalueofxisaddedby2andreassignedtoxthatisnowequalsto9.
=:simpleassignment
x=7
print(x)
7
+=:additionandassignment
x=7
x+=2
print(x)
9
-=:subtractionandassignment
x=7
x-=2
print(x)
5
*=:multiplicationandassignment
40
x=7
x*=2
print(x)
14
/=:divisionandassignment
x=7
x/=2
print(x)
3.5
%=:modulusandassignment
x=7
x%=2
print(x)
1
//=:floordivisionandassignment
x=7
x//=2
print(x)
3
41
**=:exponentiationandassignment
x=7
x**=2
print(x)
49
11.4LogicalOperators
Logical operators are used to combine statements applying booleanalgebra.
Theyare:
and:Trueonlywhenbothstatementsaretrueor:Falseonlywhenbothxandyarefalsenot:Thenotoperatorsimplyinvertstheinput,TruebecomesFalseandviceversa.
Let'sseeaprogramthatshowshoweachoneisused.
x=5
y=2
print(x==5andy>3)
print(x==5ory>3)
print(not(x==5))
False
42
True
False
11.5MembershipOperators
These operators provide an easy way to check if a certain object ispresentinasequence:string,list,tuple,set,anddictionary.
Theyare:
in:returnsTrueiftheobjectispresentnotin:returnsTrueiftheobjectisnotpresent
Let'sseeaprogramthatshowshoweachoneisused.
number_list=[1,2,4,5,6]
print(1innumber_list)
print(5notinnumber_list)
print(3notinnumber_list)
True
False
True
43
12ConditionalsConditionalsareoneofthecornerstonesofanyprogramminglanguage.
They allow you to control the program flow according to specificconditionsyoucancheck.
12.1Theifstatement
Thewayyouimplementaconditionalisthroughtheifstatement.
Thegeneralformofanifstatementis:
ifexpression:
statement
The expression contains some logic that returns a boolean, and thestatementisexecutedonlyifthereturnisTrue.
Asimpleexample:
bob_age=32
sarah_age=29
ifbob_age>sarah_age:
print('BobisolderthanSarah')
BobisolderthanSarah
44
We have two variables indicating the ages of Bob and Sarah. TheconditioninplainEnglishsays"ifBob'sageisgreaterthanSarah'sage,thenprintthephrase'BobisolderthanSarah'".
Since the condition returns True, the phrase will be printed on theconsole.
12.2Theifelseandelifstatements
In our last example, the program only does something if the conditionreturnsTrue.
Butwealsowant it todosomething if it returnsFalseorevencheckasecondorthirdconditionifthefirstonewasn'tmet.
Inthisexample,weswappedBob'sandSarah'sage.ThefirstconditionwillreturnFalsesinceSarahisoldernow,andthentheprogramwillprintthephraseaftertheelseinstead.
bob_age=29
sarah_age=32
ifbob_age>sarah_age:
print('BobisolderthanSarah')
else:
print('BobisyoungerthanSarah')
BobisyoungerthanSarah
Now,considertheexamplebelowwiththeelif.
45
bob_age=32
sarah_age=32
ifbob_age>sarah_age:
print('BobisolderthanSarah')
elifbob_age==sarah_age:
print('BobandSarahhavethesameage')
else:
print('BobisyoungerthanSarah')
BobandSarahhavethesameage
The purpose of the elif is to provide a new condition to be checkedbeforetheelseisexecuted.
Onceagainwechangedtheiragesandnowbothare32yearsold.
Assuch,theconditionintheelifismet.Sincebothhavethesameagetheprogramwillprint"BobandSarahhavethesameage".
Notice you can have as many elifs as you want, just put them insequence.
bob_age=32
sarah_age=32
ifbob_age>sarah_age:
print('BobisolderthanSarah')
elifbob_age<sarah_age:
print('BobisyoungerthanSarah')
elifbob_age==sarah_age:
print('BobandSarahhavethesameage')
else:
print('Thisoneisneverexecuted')
BobandSarahhavethesameage
46
In thisexample, theelse isneverexecutedbecauseall thepossibilitiesarecoveredinthepreviousconditionsandthuscouldberemoved.
12.3Nestedconditionals
You might need to check more than one conditional for something tohappen.
Inthiscase,youcannestyourifstatements.
Forinstance,thesecondphrase"Bobistheoldest"isprintedonlyifbothifspass.
bob_age=32
sarah_age=28
mary_age=25
ifbob_age>sarah_age:
print('BobisolderthanSarah')
ifbob_age>mary_age:
print('Bobistheoldest')
BobisolderthanSarah
Bobistheoldest
Or,dependingonthelogic,makeitsimplerwithBooleanAlgebra.
Thisway,yourcodeissmaller,morereadableandeasiertomaintain.
bob_age=32
sarah_age=28
mary_age=25
ifbob_age>sarah_ageandbob_age>mary_age:
47
print('Bobistheoldest')
Bobistheoldest
12.4TernaryOperator
Theternaryoperatorisaone-lineifstatement.
It'sveryhandyforsimpleconditions.
Thisishowitlooks:
<expression>if<condition>else<expression>
ConsiderthefollowingPythoncode:
a=25
b=50
x=0
y=1
result=xifa>belsey
print(result)
1
Hereweusefourvariables,aandbare for thecondition,whilexandyrepresenttheexpressions.
aandbare thevalueswearecheckingagainsteachother toevaluate
48
somecondition.Inthiscase,wearecheckingifaisgreaterthanb.
Iftheexpressionholdstrue,i.e.,aisgreaterthanbthenthevalueofxwillbeattributedtoresultwhichwillbeequalto0.
However, if a is less than b, then we have the value of y assigned toresult,andresultwillholdthevalue1.
Sinceaislessthanb,25<50,resultwillhave1asfinalvaluefromy.
TheeasywaytorememberhowtheconditionisevaluatedistoreaditinplainEnglish.
Ourexamplewouldread:resultwillbexifaisgreaterthanbotherwisey.
49
13ListsAspromisedintheTypeschapter,thischapterandthenextthreeaboutTuples, Sets, and Dictionaries will have more in-depth explanations ofeachof themsincetheyarevery importantandbroadlyusedstructuresinPythontoorganizeanddealwithdata.
A list has its items ordered and you can add the same item asmanytimesasyouwant.
Animportantdetailisthatlistsaremutable.
Mutabilitymeansyoucanchangealistafteritscreationbyaddingitems,removingthem,orevenjustchangingtheirvalues.
13.0.1Initialization
13.0.1.1EmptyList
people=[]
13.0.1.2Listwithinitialvalues
people=['Bob','Mary']
50
13.0.2AddinginaList
Toaddanitemintheendofalist,useappend().
people=['Bob','Mary']
people.append('Sarah')
print(people)
['Bob','Mary','Sarah']
Tospecifythepositionforthenewitem,usetheinsert()method.
people=['Bob','Mary']
people.insert(0,'Sarah')
print(people)
['Sarah','Bob','Mary']
13.0.3UpdatinginaList
Specifythepositionoftheitemtoupdateandsetthenewvalue.
people=['Bob','Mary']
people[1]='Sarah'
print(people)
['Bob','Sarah']
51
13.0.4DeletinginaList
Usetheremove()methodtodeletetheitemgivenasanargument.
people=['Bob','Mary']
people.remove('Bob')
print(people)
['Mary']
Todeleteeverybody,usetheclear()method.
people=['Bob','Mary']
people.clear()
13.0.5RetrievinginaList
Usetheindextoreferencetheitem.
Rememberthattheindexstartsat0.
Sotoaccesstheseconditemusetheindex1.
people=['Bob','Mary']
print(people[1])
Mary
52
13.0.6CheckifagivenitemalreadyexistsinaList
people=['Bob','Mary']
if'Bob'inpeople:
print('Bobexists!')
else:
print('ThereisnoBob!')
53
14TuplesAtupleissimilartoalist:it'sordered,andallowsrepetitionofitems.
Thereisjustonedifference:atupleisimmutable.
Immutability, ifyou remember,meansyoucan'tchangea tupleafter itscreation.Ifyoutrytoaddanitemorupdateone,forinstance,thePythoninterpreterwillshowyouanerror.
14.0.1Initialization
14.0.1.1EmptyTuple
people=()
14.0.1.2Tuplewithinitialvalues
people=('Bob','Mary')
14.0.2AddinginaTuple
Tuplesareimmutable.Thismeansthatifyoutrytoaddanitem,youwillseeanerror.
54
people=('Bob','Mary')
people[2]='Sarah'
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:'tuple'objectdoesnotsupportitemassignment
14.0.3UpdatinginaTuple
Updateanitemwillalsoreturnanerror.
Butthereisatrick:youcanconvertintoalist,changetheitem,andthenconvertitbacktoatuple.
people=('Bob','Mary')
people_list=list(people)
people_list[1]='Sarah'
people=tuple(people_list)
print(people)
('Bob','Sarah')
14.0.4DeletinginaTuple
Forthesamereasonyoucan'taddanitem,youalsocan'tdeleteanitem,sincetheyareimmutable.
14.0.5RetrievinginaTuple
Usetheindextoreferenceanitem.
55
people=('Bob','Mary')
print(people[1])
Mary
14.0.6CheckifagivenitemalreadyexistsinaTuple
people=('Bob','Mary')
if'Bob'inpeople:
print('Bobexists!')
else:
print('ThereisnoBob!')
56
15SetsSetsdon'tguaranteetheorderoftheitemsandarenotindexed.
Akeypointwhenusingsets:theydon'tallowrepetitionofanitem.
15.0.1Initialization
15.0.1.1EmptySet
people=set()
15.0.1.2Setwithinitialvalues
people={'Bob','Mary'}
15.0.2AddinginaSet
Usetheadd()methodtoaddoneitem.
people.add('Sarah')
Usetheupdate()methoddoaddmultipleitemsatonce.
57
people.update(['Carol','Susan'])
Remember, Sets do not allow repetition, so if you add 'Mary' again,nothingchanges.
people={'Bob','Mary'}
people.add('Mary')
print(people)
{'Bob','Mary'}
15.0.3UpdatinginaSet
Itemsinasetarenotmutable.Youhavetoeitheraddordeleteanitem.
15.0.4DeletinginaSet
ToremoveBobfromtheset:
people={'Bob','Mary'}
people.remove('Bob')
print(people)
{'Mary'}
Todeleteeverybody:
58
people.clear()
15.0.5Checkifagivenitemalreadyexistsinaset
people={'Bob','Mary'}
if'Bob'inpeople:
print('Bobexists!')
else:
print('ThereisnoBob!')
59
16DictionariesThe dictionary doesn't guarantee the order of the elements and it ismutable.
One important characteristic of dictionaries is that you can set yourcustomizedaccesskeysforeachelement.
16.0.1InitializationofaDictionary
16.0.1.1EmptyDictionary
people={}
16.0.1.2Dictionarywithinitialvalues
people={'Bob':30,'Mary':25}
16.0.2AddinginaDictionary
Ifthekeydoesn'texistyet,itisappendedtothedictionary.
people['Sarah']=32
60
16.0.3UpdatingaDictionary
Ifthekeyalreadyexists,thevalueisjustupdated.
#Bob'sageis28now
people['Bob']=28
Noticethatthecodeisprettymuchthesame.
16.0.4DeletinginaDictionary
ToremoveBobfromthedictionary:
people.pop('Bob')
Todeleteeverybody:
people.clear()
16.0.5RetrievinginaDictionary
bob_age=people['Bob']
print(bob_age)
30
61
16.0.6CheckifagivenkeyalreadyexistsinaDictionary
if'Bob'inpeople:
print('Bobexists!')
else:
print('ThereisnoBob!')
62
17whileLoopsLoops are used when you need to repeat a block of code a certainnumberoftimesorapplythesamelogicovereachiteminacollection.
Therearetwotypesofloops:forandwhile.
Youwilllearnaboutforloopsinthenextchapter.
17.1BasicSyntax
Thebasicsyntaxofawhileloopisasbelow.
whilecondition:
statement
TheloopwillcontinueuntiltheconditionisTrue.
17.2Thesquareofanumberis
The example below takes each value of number and calculates itssquaredvalue.
number=1
whilenumber<=5:
print(number,'squaredis',number**2)
number=number+1
1squaredis1
63
2squaredis4
3squaredis9
4squaredis16
5squaredis25
You can use any variable name, but I chose number because itmakessenseinthecontext.Acommongenericchoicewouldbesimplyi.
Theloopwillgoonuntilnumber(initializedwith1)islessthanorequalto5.
Notice that after the print() command, the variable number isincrementedby1totakethenextvalue.
If you don't do the incrementation you will have an infinite loop sincenumberwillnever reachavaluegreater than5.This isavery importantdetail!
17.3elseblock
WhentheconditionreturnsFalse,theelseblockwillbecalled.
number=1
whilenumber<=5:
print(number,'squaredis',number**2)
number=number+1
else:
print('Nonumbersleft!')
1squaredis1
2squaredis4
3squaredis9
4squaredis16
5squaredis25
Nonumbersleft!
64
Noticethephrase'Nonumbersleft!'isprintedaftertheloopends,thatisaftertheconditionnumber<=5evaluatestoFalse.
17.4HowtobreakoutofawhileloopinPython?
Simplyusethebreakkeyword,andtheloopwillstopitsexecution.
number=1
whilenumber<=5:
print(number,'squaredis',number**2)
number=number+1
ifnumber==4:
break
1squaredis1
2squaredis4
3squaredis9
The loop runs normally, and when number reaches 4 the if statementevaluatestoTrueandthebreakcommandiscalled.Thisfinishestheloopbeforethesquaredvalueofthenumbers4and5arecalculated.
17.5Howtoskipaniteminawhileloop
Thecontinuewilldothatforyou.
Ihadtoinverttheorderoftheifstatementandtheprint()toshowhowitworksproperly.
number=0
whilenumber<5:
65
number=number+1
ifnumber==4:
continue
print(number,'squaredis',number**2)
1squaredis1
2squaredis4
3squaredis9
5squaredis25
Theprogramalwayschecksif4isthecurrentvalueofnumber.Ifitis,thesquare of 4 won't be calculated and the continue will skip to the nextiterationwhenthevalueofnumberis5.
66
18forLoopsfor loops are similar towhile loops in the sense that they are used torepeatblocksofcode.
The most important difference is that you can easily iterate oversequentialtypes.
18.1BasicSyntax
Thebasicsyntaxofaforloopisasbelow.
foritemincollection:
statement
18.2Loopoveralist
Toloopovera listoranyothercollection, justproceedasshownin theexamplebelow.
cars=['BMW','Ferrari','McLaren']
forcarincars:
print(car)
BMW
Ferrari
McLaren
67
Thelistofcarscontainsthreeitems.Theforloopwilliterateoverthelistandstoreeachiteminthecarvariable,andthenexecuteastatement,inthiscaseprint(car),toprinteachcarintheconsole.
18.3range()function
The range function is widely used in for loops because it gives you asimplewaytolistnumbers.
Thiscodewillloopthroughthenumbers0to5andprinteachofthem.
fornumberinrange(5):
print(number)
0
1
2
3
4
Incontrast,withouttherange()function,wewoulddosomethinglikethis.
numbers=[0,1,2,3,4]
fornumberinnumbers:
print(number)
0
1
2
3
4
68
Youcanalsodefineastartandstopusingrange().
Herewearestartingin5andstopingin10.Thenumberyousettostopisnotincluded.
fornumberinrange(5,10):
print(number)
5
6
7
8
9
Finally,itisalsopossibletosetastep.
Herewe starting in 10 and incrementing by 2 until 20, since 20 is thestop,itisnotincluded.
fornumberinrange(10,20,2):
print(number)
10
12
14
16
18
18.4elseblock
Whentheitemsinthelistareover,theelseblockwillbecalled.
69
cars=['BMW','Ferrari','McLaren']
forcarincars:
print(car)
else:
print('Nocarsleft!')
BMW
Ferrari
McLaren
Nocarsleft!
18.5HowtobreakoutofaforloopinPython
Simplyusethebreakkeyword,andtheloopwillstopitsexecution.
cars=['BMW','Ferrari','McLaren']
forcarincars:
print(car)
ifcar=='Ferrari':
break
BMW
Ferrari
Theloopwilliteratethelistandprinteachcar.
In this case, after the loop reaches 'Ferrari', the break is called and'McLaren'won'tbeprinted.
18.6Howtoskipaniteminaforloop
Inthissection,we'lllearnhowcontinuecandothisforyou.
I had to invert the order of the if statement and the continue to show
70
howitworksproperly.
Notice that Ialwayscheck if 'Ferrari' is thecurrent item. If it is, 'Ferrari'won'tbeprinted,andthecontinuewillskiptothenextitem'McLaren'.
cars=['BMW','Ferrari','McLaren']
forcarincars:
ifcar=='Ferrari':
continue
print(car)
BMW
McLaren
18.7LoopoveraLoop:NestedLoops
Sometimesyouhavemorecomplexcollections,likealistoflists.
Toiterateovertheselists,youneednestedforloops.
In thiscase, Ihave three lists:oneofBMWmodels,anotheronFerrarimodels,andfinallyonewithMcLarenmodels.
The first loop iteratesovereachbrand's list,and thesecondwill iterateoverthemodelsofeachbrand.
car_models=[
['BMWI8','BMWX3',
'BMWX1'],
['Ferrari812','FerrariF8',
'FerrariGTC4'],
['McLaren570S','McLaren570GT',
'McLaren720S']
]
71
forbrandincar_models:
formodelinbrand:
print(model)
BMWI8
BMWX3
BMWX1
Ferrari812
FerrariF8
FerrariGTC4
McLaren570S
McLaren570GT
McLaren720S
18.8LoopoverotherDataStructures
Thesamelogicshowntoapplyforloopsoveralistcanbeextendedtotheotherdatastructures:tuple,set,anddictionary.
I will briefly demonstrate how to make a basic loop over each one ofthem.
18.8.1LoopoveraTuple
people=('Bob','Mary')
forpersoninpeople:
print(person)
Bob
Mary
18.8.2LoopoveraSet
72
people={'Bob','Mary'}
forpersoninpeople:
print(person)
Bob
Mary
18.8.3LoopoveraDictionary
Toprintthekeys:
people={'Bob':30,'Mary':25}
forpersoninpeople:
print(person)
Bob
Mary
Toprintthevalues:
people={'Bob':30,'Mary':25}
forpersoninpeople:
print(people[person])
30
25
73
19FunctionsAs the code grows the complexity also grows. And functions helporganizethecode.
Functionsareahandywaytocreateblocksofcodethatyoucanreuse.
19.1DefinitionandCalling
InPythonusethedefkeywordtodefineafunction.
Giveitanameanduseparenthesestoinform0ormorearguments.
In the line after the declaration starts, remember to indent the block ofcode.
Hereisanexampleofafunctioncalledprint_first_function()thatonlyprintsaphrase'Myfirstfunction!'.
Tocallthefunctionjustuseitsnameasdefined.
defprint_first_function():
print('Myfirstfunction!')
print_first_function()
Myfirstfunction!
19.2returnavalue
74
Usethereturnkeywordtoreturnavaluefromthefunction.
In this example the function second_function() returns the string 'Mysecondfunction!'.
Notice thatprint() is a built-in functionandour function is called frominsideit.
Thestring returnedbysecond_function() ispassedasargument to theprint()function.
defsecond_function():
return'Mysecondfunction!'
print(second_function())
Mysecondfunction!
19.3returnmultiplevalues
Functionscanalsoreturnmultiplevaluesatonce.
return_numbers()returnstwovaluessimultaneously.
defreturn_numbers():
return10,2
print(return_numbers())
(10,2)
75
19.4Arguments
Youcandefineparametersbetweentheparentheses.
When calling a function with parameters you have to pass argumentsaccordingtotheparametersdefined.
The past examples had no parameters, so there was no need forarguments. The parentheses remained emptywhen the functionswerecalled.
19.4.1OneArgument
Tospecifyoneparameter,justdefineitinsidetheparentheses.
Inthisexample,thefunctionmy_numberexpectsonenumberasargumentdefinedbytheparameternum.
The value of the argument is then accessible inside the function to beused.
defmy_number(num):
return'Mynumberis:'+str(num)
print(my_number(10))
Mynumberis:10
19.4.2TwoormoreArguments
76
Todefinemoreparameters,justuseacommatoseparatethem.
Herewehaveafunctionthataddstwonumberscalledadd,itexpectstwoargumentsdefinedbyfirst_numandsecond_num.
The arguments are added by the + operator and the result is thenreturnedbythereturn.
defadd(first_num,second_num):
returnfirst_num+second_num
print(add(10,2))
12
Thisexampleisverysimilartothelastone.Theonlydifferenceisthatwehave3parametersinsteadof2.
defadd(first_num,second_num,third_num):
returnfirst_num+second_num+third_num
print(add(10,2,3))
15
Thislogicofdefiningparametersandpassingargumentsisthesameforanynumberofparameters.
It is important topointout that theargumentshave tobepassed in thesameorderthattheparametersaredefined.
77
19.4.3Defaultvalue.
Youcansetadefaultvalueforaparameterifnoargumentisgivenusingthe=operatorandavalueofchoice.
Inthisfunction,ifnoargumentisgiven,thenumber30isassumedastheexpectedvaluebydefault.
defmy_number(my_number=30):
return'Mynumberis:'+str(my_number)
print(my_number(10))
print(my_number())
Mynumberis:10
Mynumberis:30
19.4.4KeywordorNamedArguments
Whencallinga function, theorderof theargumentshave tomatch theorderoftheparameters.
Thealternativeisifyouusekeywordornamedarguments.
Settheargumentstotheirrespectiveparametersdirectlyusingthenameoftheparametersandthe=operators.
This example flips the arguments, but the function works as expectedbecauseItellwhichvaluegoestowhichparameterbyname.
78
defmy_numbers(first_number,second_number):
return'Thenumbersare:'+str(first_number)+'and'+str(second_number)
print(my_numbers(second_number=30,first_number=10))
Thenumbersare:10and30
19.4.5Anynumberofarguments:*args
If you don't want to specify the number of parameters, just use the *before the parameter name. Then the function will take as manyargumentsasnecessary.
The parameter name could be anything like *numbers, but there is aconventioninPythontouse*argsforthisdefinitionofavariablenumberofarguments.
defmy_numbers(*args):
forarginargs:
print(arg)
my_numbers(10,2,3)
10
2
3
19.4.6AnynumberofKeyword/Namedarguments:**kwargs
Similar to *args, we can use **kwargs to pass as many keyword
79
argumentsaswewant,aslongasweuse**.
Again, the name could be anything like **numbers, but **kwargs is aconvention.
defmy_numbers(**kwargs):
forkey,valueinkwargs.items():
print(key)
print(value)
my_numbers(first_number=30,second_number=10)
first_number
30
second_number
10
19.4.7Othertypesasarguments
Thepastexamplesusedmainlynumbers,butyoucanpassanytypeasargumentandtheywillbetreatedassuchinsidethefunction.
Thisexampleistakingstringsasarguments.
defmy_sport(sport):
print('Ilike'+sport)
my_sport('football')
my_sport('swimming')
Ilikefootball
Ilikeswimming
80
Thisfunctiontakesalistasargument.
defmy_numbers(numbers):
fornumberinnumbers:
print(number)
my_numbers([30,10,64,92,105])
30
10
64
92
105
81
20ScopeThe place where a variable is created defines its availability to beaccessed and manipulated by the rest of the code. This is known asscope.
Therearetwotypesofscope:localandglobal.
20.1GlobalScope
Aglobalscopeallowsyoutousethevariableanywhereinyourprogram.
Ifyourvariableisoutsideafunction,ithasglobalscopebydefault.
name='Bob'
defprint_name():
print('Mynameis'+name)
print_name()
MynameisBob
NoticethatthefunctioncouldusethevariablenameandprintMynameisBob.
20.2LocalScope
Whenyoudeclareavariable insidea function, it onlyexists inside that
82
functionandcan'tbeaccessedfromtheoutside.
defprint_name():
name="Bob"
print('Mynameis'+name)
print_name()
MynameisBob
The variable name was declared inside the function, the output is thesameasbefore.
Butthiswillthrowanerror:
defprint_name():
name='Bob'
print('Mynameis'+name)
print(name)
Theoutputofthecodeaboveis:
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
NameError:name'name'isnotdefined
Itriedtoprintthevariablenamefromoutsidethefunction,butthescopeofthevariablewaslocalandcouldnotbefoundinaglobalscope.
20.3MixingScopes
83
Ifyouusethesamenameforvariablesinsideandoutsideafunction,thefunctionwillusetheoneinsideitsscope.
So when you call print_name(), the name='Bob' is used to print thephrase.
On the other hand, when calling print() outside the function scope,name="Sarah"isusedbecauseofitsglobalscope.
name="Sarah"
defprint_name():
name='Bob'
print('Mynameis'+name)
print_name()
print(name)
Theoutputofthecodeaboveis:
MynameisBob
Sarah
84
21ListComprehensionsSometimes we want to perform some very simple operations over theitemsofalist.
List comprehensions give us a succinct way to work on lists as analternativetoothermethodsofiteration,suchasforloops.
21.1Basicsyntax
Tousealistcomprehensiontoreplacearegularforloop,wecanmake:
[expressionforiteminlist]
Whichisthesameasdoing:
foriteminlist:
expression
Ifwewantsomeconditionaltoapplytheexpression,wehave:
[expressionforiteminlistifconditional]
Whichisthesameasdoing:
foriteminlist:
85
ifconditional:
expression
21.2Example1:calculatingthecubeofanumber
Regularway
numbers=[1,2,3,4,5]
new_list=[]
forninnumbers:
new_list.append(n**3)
print(new_list)
[1,8,27,64,125]
Usinglistcomprehensions
numbers=[1,2,3,4,5]
new_list=[]
new_list=[n**3forninnumbers]
print(new_list)
[1,8,27,64,125]
21.3Example2:calculatingthecubeofanumberonlyifitisgreaterthan3
86
Using the conditional, we can filter only the values we want theexpressiontobeappliedto.
Regularway
numbers=[1,2,3,4,5]
new_list=[]
forninnumbers:
if(n>3):
new_list.append(n**3)
print(new_list)
[64,125]
Usinglistcomprehensions
numbers=[1,2,3,4,5]
new_list=[]
new_list=[n**3forninnumbersifn>3]
print(new_list)
[64,125]
21.4Example3:callingfunctionswithlistcomprehensions
Wecanalsocallfunctionsusingthelistcomprehensionsyntax:
87
numbers=[1,2,3,4,5]
new_list=[]
defcube(number):
returnnumber**3
new_list=[cube(n)forninnumbersifn>3]
print(new_list)
[64,125]
88
22LambdaFunctionsAPythonlambdafunctioncanonlyhaveoneexpressionandcan'thavemultiplelines.
It is supposed tomake it easier to create some small logic in one lineinsteadofawholefunctionasitisusuallydone.
Lambdafunctionsarealsoanonymous,whichmeansthereisnoneedtonamethem.
22.1BasicSyntax
Thebasicsyntaxisverysimple:justusethelambdakeyword,definetheparameters needed, use ":" to separate the parameters from theexpression.
Thegeneralformis:
lambdaarguments:expression
22.1.1Oneparameterexample
Lookatthisexampleusingonlyoneparameter.
cubic=lambdanumber:number**3
print(cubic(2))
89
8
22.1.2Multipleparameterexample
Ifyouwant,youcanalsohavemultipleparameters.
exponential=lambdamultiplier,number,exponent:multiplier*number**exponent
print(exponential(2,2,3))
16
22.1.3CallingtheLambdaFunctiondirectly
Youdon'tneedtouseavariableaswedidbefore,youcanmakeuseofparenthesisaroundthe lambdafunctionandanotherpairofparenthesisaroundthearguments.
Thedeclarationofthefunctionandtheexecutionwillhappeninthesameline.
(lambdamultiplier,number,exponent:multiplier*number**exponent)(2,2,3)
16
22.2Examplesusinglambdafunctionswithotherbuilt-infunctions
90
22.2.1Map
TheMapfunctionappliestheexpressiontoeachiteminalist.
Let'scalculatethecubicofeachnumberinthelist.
numbers=[2,5,10]
cubics=list(map(lambdanumber:number**3,numbers))
print(cubics)
[8,125,1000]
22.2.2Filter
TheFilterfunctionwillfilterthelistbasedontheexpression.
Let'sfiltertohaveonlythenumbersgreaterthan5.
numbers=[2,5,10]
filtered_list=list(filter(lambdanumber:number>5,numbers))
print(filtered_list)
[10]
91
23ModulesAfter some time your code starts to get more complex with lots offunctionsandvariables.
TomakeiteasiertoorganizethecodeweuseModules.
A well-designedModule also has the advantage of being reusable, soyouwritecodeonceandreuseiteverywhere.
Youcanwriteamodulewithall themathematicaloperationsandotherpeoplecanuseit.
And, ifyouneed,youcanusesomeoneelse'smodulestosimplifyyourcode,speedingupyourproject.
Inotherprogramminglanguages,thesearealsoreferredtoaslibraries.
23.1UsingaModule
Touseamoduleweusetheimportkeyword.
Asthenameimplieswehavetotellourprogramwhatmoduletoimport.
Afterthat,wecanuseanyfunctionavailableinthatmodule.
Let'sseeanexampleusingthemathmodule.
First,let'sseehowtohaveaccesstoaconstant,Euler'snumber.
92
importmath
math.e
2.718281828459045
Inthissecondexample,wearegoingtouseafunctionthatcalculatesthesquarerootofanumber.
Itisalsopossibletousetheaskeywordtocreateanalias.
importmathasm
m.sqrt(121)
m.sqrt(729)
11
27
Finally, using the from keyword, we can specify exactly what to importinstead of the whole module and use the function directly without themodule'sname.
This example uses the floor() function that returns the largest integerlessthanorequaltoagivennumber.
frommathimportfloor
floor(9.8923)
93
9
23.2CreatingaModule
Nowthatweknowhowtousemodules,let'sseehowtocreateone.
It isgoingtobeamodulewiththebasicmathoperationsadd,subtract,multiply,divideanditisgonnabecalledbasic_operations.
Createthebasic_operations.pyfilewiththefourfunctions.
defadd(first_num,second_num):
returnfirst_num+second_num
defsubtract(first_num,second_num):
returnfirst_num-second_num
defmultiply(first_num,second_num):
returnfirst_num*second_num
defdivide(first_num,second_num):
returnfirst_num/second_num
Then,justimportthebasic_operationsmoduleandusethefunctions.
importbasic_operations
basic_operations.add(10,2)
basic_operations.subtract(10,2)
basic_operations.multiply(10,2)
basic_operations.divide(10,2)
12
8
20
5.0
94
24if__name__=='__main__'You are on the process of building a module with the basic mathoperationsadd,subtract,multiply,dividecalledbasic_operationssavedinthebasic_operations.pyfile.
Toguaranteeeverythingisfine,youcanrunsometests.
defadd(first_num,second_num):
returnfirst_num+second_num
defsubtract(first_num,second_num):
returnfirst_num-second_num
defmultiply(first_num,second_num):
returnfirst_num*second_num
defdivide(first_num,second_num):
returnfirst_num/second_num
print(add(10,2))
print(subtract(10,2))
print(multiply(10,2))
print(divide(10,2))
Afterrunningthecode:
renan@pro-home:~$python3basic_operations.py
Theoutputis:
12
8
20
5.0
95
Theoutputforthosetestsarewhatweexpected.
Ourcodeisrightandreadytoshare.
Let'simportthenewmoduleandrunitinthePythonconsole.
Python3.6.9(default,Nov72019,10:44:02)
[GCC8.3.0]onlinux
Type"help","copyright","credits"or"license"formoreinformation.
>>>importbasic_operations
12
8
20
5.0
>>>
Whenthemoduleisimportedourtestsaredisplayedonthescreeneventhoughwedidn'tdoanythingbesidesimportingbasic_operations.
Tofixthatweuseif__name__=='__main__'inthebasic_operations.pyfilelikethis:
defadd(first_num,second_num):
returnfirst_num+second_num
defsubtract(first_num,second_num):
returnfirst_num-second_num
defmultiply(first_num,second_num):
returnfirst_num*second_num
defdivide(first_num,second_num):
returnfirst_num/second_num
if__name__=='__main__':
print(add(10,2))
print(subtract(10,2))
print(multiply(10,2))
96
print(divide(10,2))
Running the code directly on the terminal will continue to display thetests.Butwhenyouimportitlikeamodule,thetestswon'tshowandyoucanusethefunctionsthewayyouintended.
Python3.6.9(default,Nov72019,10:44:02)
[GCC8.3.0]onlinux
Type"help","copyright","credits"or"license"formoreinformation.
>>>importbasic_operations
>>>basic_operations.multiply(10,2)
20
>>>
Now that you know how to use the if __name__ == '__main__', let'sunderstandhowitworks.
Theconditiontellswhentheinterpreteristreatingthecodeasamoduleorasaprogramitselfbeingexecuteddirectly.
Pythonhasthisnativevariablecalled__name__.
Thisvariablerepresentsthenameofthemodulewhichisthenameofthe.pyfile.
Createafilemy_program.pywiththefollowingandexecuteit.
print(__name__)
Theoutputwillbe:
97
__main__
This tells us that when a program is executed directly, the variable__name__isdefinedas__main__.
Butwhenitisimportedasamodule,thevalueof__name__isthenameofthemodule.
Python3.6.9(default,Nov72019,10:44:02)
[GCC8.3.0]onlinux
Type"help","copyright","credits"or"license"formoreinformation.
>>>importmy_program
my_program
>>>
This is how the Python interpreter differentiates the behavior of animportedmoduleandaprogramexecuteddirectlyintheterminal.
98
25FilesCreating,deleting,reading,andmanyotherfunctionsappliedtofilesareanintegralpartofmanyprograms.
Assuch,itisveryimportanttoknowhowtoorganizeanddealwithfilesdirectlyfromyourcode.
Let'sseehowtohandlefilesinPython.
25.1Filecreate
Firstthingsfirst,create!
Wearegoingtousetheopen()function.
Thisfunctionopensafileandreturnsitscorrespondingobject.
The first argument is the nameof the fileweare handling, the secondreferstotheoperationweareusing.
Thecodebelowcreatesthefile"people.txt",thexargumentisusedwhenwejustwanttocreatethefile.Ifafilewiththesamenamealreadyexists,itwillthrowanexception.
people_file=open("people.txt","x")
Youcanalsowethewmodetocreateafile.Unlikethexmode,itwillnot
99
throwanexceptionsince thismode indicates thewritingmode.Weareopeningafiletowritedataintoitand,ifthefiledoesn'texist,itiscreated.
people_file=open("people.txt","w")
The last one is the a mode which stands for append. As the nameimplies,youcanappendmoredata to the file,while thewmodesimplyoverwritesanyexistingdata.
Whenappending,ifthefiledoesn'texist,italsocreatesit.
people_file=open("people.txt","a")
25.2Filewrite
Towritedataintoafile,yousimplyopenafilewiththewmode.
Then,toadddata,youusetheobjectreturnedbytheopen()function,inthiscase, theobject iscalledpeople_file.Thencall thewrite() functionpassingthedataasargument.
people_file=open("people.txt","w")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()
Weuse\nat theendtobreakthe line,otherwisethecontent in thefile
100
willstayinthesamelineas"BobMarySarah".
Onemoredetailistoclose()thefile.Thisisnotonlyagoodpractice,butalsoensuresthatyourchangeswereappliedtothefile.
Rememberthatwhenusingwmode,thedatathatalreadyexistedinthefilewillbeoverwrittenby thenewdata.Toaddnewdatawithout losingwhatwasalreadythere,wehavetousetheappendmode.
25.3Fileappend
Theamodeappendsnewdatatothefile,keepingtheexistingone.
In this example, after the first writingwith wmode, we are using the amodetoappend.Theresultisthateachnamewillappeartwiceinthefile"people.txt".
#firstwrite
people_file=open("people.txt","w")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()
#appendingmoredata
#keepingtheexistingdata
people_file=open("people.txt","a")
people_file.write("Bob\n")
people_file.write("Mary\n")
people_file.write("Sarah\n")
people_file.close()
25.4Fileread
101
Readingthefileisalsoverystraightforward:justusethermodelikeso.
If you read the "people.txt" file created in the last example, you shouldsee6namesinyouroutput.
people_file=open("people.txt","r")
print(people_file.read())
Bob
Mary
Sarah
Bob
Mary
Sarah
Theread()functionreadsthewholefileatonceifyouusethereadline()function,youcanreadthefilelinebyline.
people_file=open("people.txt","r")
print(people_file.readline())
print(people_file.readline())
print(people_file.readline())
Bob
Mary
Sarah
Youcanalsoalooptoreadthelinesliketheexamplebelow.
people_file=open("people.txt","r")
forpersoninpeople_file:
print(person)
102
Bob
Mary
Sarah
Bob
Mary
Sarah
25.5DeleteaFile
Todeleteafile,youalsoneedtheosmodule.
Usetheremove()method.
importos
os.remove('my_file.txt')
25.6CheckifaFileExists
Usetheos.path.exists()methodtochecktheexistenceofafile.
importos
ifos.path.exists('my_file.txt'):
os.remove('my_file.txt')
else:
print('Thereisnosuchfile!')
25.7CopyaFile
Forthisone,Iliketousethecopyfile()methodfromtheshutilmodule.
fromshutilimportcopyfile
103
copyfile('my_file.txt','another_file.txt')
Thereareafewoptionstocopyafile,butcopyfile()isthefastestone.
25.8RenameandMoveaFile
Ifyouneedtomoveorrenameafileyoucanusethemove()methodfromtheshutilmodule.
fromshutilimportmove
move('my_file.txt','another_file.txt')
104
26ClassesandObjectsClasses and Objects are the fundamental concepts of Object-OrientedProgramming.
InPython,everythingisanobject!
Avariable(object)isjustaninstanceofitstype(class).
That'swhywhenyoucheckthetypeofavariableyoucanseetheclasskeywordrightnexttoitstype(class).
Thiscodesnippetshowsthatmy_cityisanobjectanditisaninstanceoftheclassstr.
my_city="NewYork"
print(type(my_city))
<class'str'>
26.1DifferentiateClassxObject
Theclassgivesyouastandardway tocreateobjects.Aclass is likeabaseproject.
SayyouareanengineerworkingforBoeing.
Your newmission is to build the new product for the company, a new
105
model called 747-Space. This aircraft flies higher altitudes than othercommercialmodels.
Boeingneedstobuilddozensofthosetoselltoairlinesallovertheworld,andtheaircraftshavetobeallthesame.
Toguaranteethat theaircrafts(objects) followthesamestandards,youneedtohaveaproject(class)thatcanbereplicable.
Theclassisaproject,ablueprintforanobject.
Thiswayyoumaketheprojectonce,andreuseitmanytimes.
In our code example before, consider that every string has the samebehaviorand thesameattributes.So itonlymakessense forstrings tohaveaclassstrtodefinethem.
26.2AttributesandMethods
Objectshavesomebehaviorwhichisisgivenbyattributesandmethods.
Insimpleterms, in thecontextofanobject,attributesarevariablesandmethodsarefunctionsattachedtoanobject.
Forexample,astringhasmanybuilt-inmethodsthatwecanuse.
Theyworklikefunctions,youjustneedtothemfromtheobjectsusinga..
In this code snippet, I'm calling the replace() method from the string
106
variablemy_citywhichisanobject,andaninstanceoftheclassstr.
The replace() method replaces a part of the string for another andreturns a new string with the change. The original string remains thesame.
Let'sreplace'New'for'Old'in'NewYork'.
my_city='NewYork'
print(my_city.replace('New','Old'))
print(my_city)
OldYork
NewYork
26.3CreatingaClass
Wehaveusedmanyobjects(instancesofclasses)likestrings,integers,lists,anddictionaries.AllofthemareinstancesofpredefinedclassesinPython.
Tocreateourownclassesweusetheclasskeyword.
Byconvention, thenameof theclassmatches thenameof the.py fileand themodulebyconsequence. It isalsoagoodpractice toorganizethecode.
Createafilevehicle.pywiththefollowingclassVehicle.
classVehicle:
107
def__init__(self,year,model,plate_number,current_speed=0):
self.year=year
self.model=model
self.plate_number=plate_number
self.current_speed=current_speed
defmove(self):
self.current_speed+=1
defaccelerate(self,value):
self.current_speed+=value
defstop(self):
self.current_speed=0
defvehicle_details(self):
returnself.model+','+str(self.year)+','+self.plate_number
Let'sbreakdowntheclasstoexplainitinparts.
TheclasskeywordisusedtospecifythenameoftheclassVehicle.
The __init__ function is a built-in function that all classes have, it iscalled when an object is created and is often used to initialize theattributes,assigningvaluestothem,similartowhatisdonetovariables.
The first parameter self in the __init__ function is a reference to theobject(instance)itself.Wecallitselfbyconventionandithastobethefirst parameter in every instancemethod, as you can see in the othermethod definitions def move(self), def accelerate(self, value), defstop(self),anddefvehicle_details(self).
Vehiclehas4attributes:year,model,plate_number,andcurrent_speed.
Inside the__init__,eachoneof them is initializedwith theparametersgivenwhentheobjectisinstantiated.
108
Notice thatcurrent_speed is initializedwith0bydefault,meaning that ifnovalueisgiven,current_speedwillbeequalto0whentheobjectisfirstinstantiated.
Finally,we have threemethods tomanipulate our vehicle regarding itsspeed:defmove(self),defaccelerate(self,value),defstop(self).
And one method to give back information about the vehicle: defvehicle_details(self).
The implementation inside the methods work the same way as infunctions.Youcanalsohaveareturntogiveyoubacksomevalueattheendofthemethodasdemonstratedbydefvehicle_details(self).
26.4UsingtheClass
Use the classona terminal, import theVehicle class from thevehiclemodule.
Create an instance calledmy_car, initializingyearwith 2009,modelwith'F8',plate_numberwith'ABC1234',andcurrent_speedwith100.
Theselfparameterisnottakenintoconsiderationwhencallingmethods.The Python interpreter infers its value as being the currentobject/instance automatically, so we just have to pass the otherargumentswheninstantiatingandcallingmethods.
Nowusethemethodstomove()thecarwhichincreasesitscurrent_speedby 1, accelerate(10) which increases its current_speed by the value
109
givenintheargument,andstop()whichsetsthecurrent_speedto0.
Remembertoprintthevalueofcurrent_speedateverycommandtoseethechanges.
To finish the test, call vehicle_details() to print the information aboutourvehicle.
>>>fromvehicleimportVehicle
>>>
>>>my_car=Vehicle(2009,'F8','ABC1234',100)
>>>print(my_car.current_speed)
100
>>>my_car.move()
>>>print(my_car.current_speed)
101
>>>my_car.accelerate(10)
>>>print(my_car.current_speed)
111
>>>my_car.stop()
>>>print(my_car.current_speed)
0
>>>print(my_car.vehicle_details())
F8,2009,ABC1234
Ifwedon'tsettheinitialvalueforcurrent_speed,itwillbezerobydefaultasstatedbeforeanddemonstratedinthenextexample.
>>>fromvehicleimportVehicle
>>>
>>>my_car=Vehicle(2009,'F8','ABC1234')
>>>print(my_car.current_speed)
0
>>>my_car.move()
>>>print(my_car.current_speed)
1
>>>my_car.accelerate(10)
>>>print(my_car.current_speed)
11
>>>my_car.stop()
110
>>>print(my_car.current_speed)
0
>>>print(my_car.vehicle_details())
F8,2009,ABC1234
111
27InheritanceLet'sdefineagenericVehicleclassandsaveitinsidethevehicle.pyfile.
classVehicle:
def__init__(self,year,model,plate_number,current_speed):
self.year=year
self.model=model
self.plate_number=plate_number
self.current_speed=current_speed
defmove(self):
self.current_speed+=1
defaccelerate(self,value):
self.current_speed+=value
defstop(self):
self.current_speed=0
defvehicle_details(self):
returnself.model+','+str(self.year)+','+self.plate_number
Avehiclehasattributesyear,model,plate_number,andcurrent_speed.
Thedefinitionofvehicle intheVehicle isverygenericandmightnotbesuitablefortrucksforinstancebecauseitshouldincludeacargoattribute.
Ontheotherhand,acargoattributedoesnotmakemuchsenseforsmallvehicleslikemotorcycles.
Tosolvethiswecanuseinheritance.
Whenaclass(child)inheritsanotherclass(parent),alltheattributesandmethodsfromtoparentclassareinheritedbythechildclass.
112
27.1ParentandChild
In our case, we want a new Truck class to inherit everything from theVehicle class. Then we want it to add its own specific attributecurrent_cargotocontroltheadditionandremovalofcargofromthetruck.
TheTruckclass iscalledachildclassthat inherits fromitsparentclassVehicle.
A parent class is also called a superclass while a child class is alsoknownasasubclass.
CreatetheclassTruckandsaveitinsidethetruck.pyfile.
fromvehicleimportVehicle
classTruck(Vehicle):
def__init__(self,year,model,plate_number,current_speed,current_cargo):
super().__init__(year,model,plate_number,current_speed)
self.current_cargo=current_cargo
defadd_cargo(self,cargo):
self.current_cargo+=cargo
defremove_cargo(self,cargo):
self.current_cargo-=cargo
Let'sbreakdowntheclasstoexplainitinparts.
TheclassVehicle insidetheparentheseswhendefiningtheclassTruckindicatesthattheparentVehicleisbeinginheritedbyitschildTruck.
The__init__methodhasselfasitsfirstparameter,asusual.
113
Theparametersyear,model,plate_number,andcurrent_speedare theretomatchtheonesintheVehicleclass.
Weaddedanewparametercurrent_cargosuitedfortheTruckclass.
Inthefirstlineofthe__init__methodoftheTruckclasswehavetocallthe__init__methodoftheVehicleclass.
To do that we use super() to make a reference to the supperclassVehicle, so when super().__init__(year, model, plate_number,
current_speed)iscalledweavoidrepetitionofourcode.
Afterthat,wecanassignthevalueofcurrent_cargonormally.
Finally, we have two methods to deal with the current_cargo: defadd_cargo(self,cargo):,anddefremove_cargo(self,cargo):.
Remember that Truck inherits attributes andmethods from Vehicle, sowe also have an implicit access to the methods that manipulate thespeed:defmove(self),defaccelerate(self,value),defstop(self).
27.2UsingtheTruckclass
Use the class in your terminal, import the Truck class from the truckmodule.
Createaninstancecalledmy_truck,initializingyearwith2015,modelwith'V8', plate_number with 'XYZ1234', current_speed with 0, andcurrent_cargowith0.
114
Useadd_cargo(10) toincreasecurrent_cargoby10,remove_cargo(4), todecreasecurrent_cargoby4.
Remembertoprintthevalueofcurrent_cargoateverycommandtoseethechanges.
Byinheritance,wecanusethemethodsfromtheVehicleclasstomove()the truckwhich increases itscurrent_speed by1,accelerate(10)whichincreases its current_speed by the value given in the argument, andstop()whichsetsthecurrent_speedto0.
Remembertoprintthevalueofcurrent_speedateveryinteractiontoseethechanges.
Tofinishthetest,callvehicle_details()inheritedfromtheVehicleclasstoprinttheinformationaboutourtruck.
>>>fromtruckimportTruck
>>>
>>>my_truck=Truck(2015,'V8','XYZ1234',0,0)
>>>print(my_truck.current_cargo)
0
>>>my_truck.add_cargo(10)
>>>print(my_truck.current_cargo)
10
>>>my_truck.remove_cargo(4)
>>>print(my_truck.current_cargo)
6
>>>print(my_truck.current_speed)
0
>>>my_truck.accelerate(10)
>>>print(my_truck.current_speed)
10
>>>my_truck.stop()
>>>print(my_truck.current_speed)
0
>>>print(my_truck.vehicle_details())
V8,2015,XYZ1234
115
116
28ExceptionsErrors are a part of every programmer's life, and knowing how to dealwiththemisaskillonitsown.
ThewayPythondealswitherrorsiscalled'ExceptionHandling'.
Ifsomepieceofcoderunsintoanerror,thePythoninterpreterwillraiseanexception.
28.1TypesofExceptions
Let's try to raise some exceptions on purpose and see the errors theyproduce.
TypeError
First,trytoaddastringandaninteger:
'Iamastring'+32
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
TypeError:mustbestr,notint
IndexError
Now,trytoaccessanindexthatdoesn'texistinalist.
117
Acommonmistake is to forget thatsequencesare0-indexed,meaningthefirstitemhasindex0,not1.
Inthisexample,thelistcar_brandsendsatindex2.
car_brands=['ford','ferrari','bmw']
print(car_brands[3])
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
IndexError:listindexoutofrange
NameError
Ifwetrytoprintavariablethatdoesn'texist.
print(my_variable)
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
NameError:name'my_variable'isnotdefined
ZeroDivisionError
Mathdoesn'tallowdivisionbyzero,tryingtodosowillraiseanerror,asexpected.
32/0
118
Traceback(mostrecentcalllast):
File"<stdin>",line1,in<module>
ZeroDivisionError:divisionbyzero
Thiswasjustasampleofthekindsofexceptionsyoumightseeonyourdailyroutineandwhatcancauseeachofthem.
28.2ExceptionHandling
Nowweknowhowtocauseerrorsthatwillcrashourcodeandshowsussomemessagesayingsomethingiswrong.
Tohandletheseexceptionsjustmakeuseofthetry/exceptstatement.
try:
32/0
except:
print('Dividingbyzero!')
Dividingbyzero!
Theexampleaboveshowstheuseofthetrystatement.
Puttheblockofcodethatmaycauseanexceptioninsidethetryscope.If everything runs alright, the except block is not invoked. But if anexceptionisraised,theblockofcodeinsidetheexceptisexecuted.
Thiswaytheprogramdoesn'tcrashandifyouhavesomecodeaftertheexception,itwillkeeprunningifyouwantto.
28.3SpecificExceptionHandling
119
In the last example the except block was generic, meaning it wascatchinganything.
Goodpractice it tospecify the typeofexceptionweare trying tocatch,whichhelpsalotwhendebuggingthecodelater.
If you know a block of code can throw an IndexError, specify it in theexcept:
try:
car_brands=['ford','ferrari','bmw']
print(car_brands[3])
exceptIndexError:
print('Thereisnosuchindex!')
Thereisnosuchindex!
Youcanuseatupletospecifyasmanyexceptionstypesasyouwantinasingleexcept:
try:
print('Mycode!')
except(IndexError,ZeroDivisionError,TypeError):
print('MyExcepetion!')
28.4else
It is possible to addanelse commandat the endof thetry/except. Itrunsonlyiftherearenoexceptions.
120
my_variable='Myvariable'
try:
print(my_variable)
exceptNameError:
print('NameErrorcaught!')
else:
print('NoNameError')
Myvariable
NoNameError
28.5RaisingExceptions
Theraisecommandallowsyoutomanuallyraiseanexception.
This is particularly useful if you want to catch an exception and dosomethingwith it -- like logging theerror insomepersonalizedway likeredirecting it to a log aggregator, or ending the execution of the codesincetheerrorshouldnotallowtheprogressoftheprogram.
try:
raiseIndexError('Thisindexisnotallowed')
except:
print('Doingsomethingwiththeexception!')
raise
Doingsomethingwiththeexception!
Traceback(mostrecentcalllast):
File"<stdin>",line2,in<module>
IndexError:Thisindexisnotallowed
28.6finally
121
Thefinallyblock isexecutedindependentlyofexceptionsbeingraisedornot.
Theyareusually there to allow theprogram to cleanup resources likefiles,memory,networkconnections,etc.
try:
print(my_variable)
exceptNameError:
print('Exceptblock')
finally:
print('Finallyblock')
Exceptblock
Finallyblock
122
29ConclusionThat'sit!
Congratulationsonreachingtheend.
Iwanttothankyouforreadingthisbook.
Ifyouwanttolearnmore,checkoutmyblogrenanmf.com.
Let me know if you have any suggestions by reaching out to me [email protected].
Youcanalsofindmeas@renanmourafon:
Twitter:https://twitter.com/renanmourafLinkedin:https://www.linkedin.com/in/renanmourafInstagram:https://www.instagram.com/renanmouraf
123