unit 5 python reference
TRANSCRIPT
-
8/2/2019 Unit 5 Python Reference
1/11
PythonReference
cs101:Unit5(includesUnits1-5)
ArithmeticExpressions
addition: +
outputsthesumofthetwoinputnumbers
multiplication: *
outputstheproductofthetwoinputnumbers
subtraction: -
outputsthedifferencebetweenthetwoinputnumbers
division: /
outputstheresultofdividingthefirstnumberbythesecond
Note:ifbothnumbersarewholenumbers,theresultistruncatedtojustthewhole
numberpart.
modulo: %
outputstheremainderofdividingthefirstnumberbythesecond
exponentiation: **
outputstheresultofraising tothepower(multiplyingbyitself
numberoftimes).
Comparisons
equality: ==
outputsTrueifthetwoinputvaluesareequal, Falseotherwise
inequality: !=
outputsTrueifthetwoinputvaluesarenotequal, Falseotherwise
greaterthan: >
outputsTrueifNumber1isgreaterthanNumber2
lessthan: =
outputsTrueifNumber1isnotlessthanNumber2
lessthanorequalto:
-
8/2/2019 Unit 5 Python Reference
2/11
VariablesandAssignment
Names
AinPythoncanbeanysequenceofletters,numbers,andunderscores( _)thatdoesnotstart
withanumber.Weusuallyusealllowercaselettersforvariablenames,butcapitalizationmustmatch
exactly.HerearesomevalidexamplesofnamesinPython(butmostofthesewouldnotbegood
choicestoactuallyuseinyourprograms):
my_name
one2one
Dorina
this_is_a_very_long_variable_name
AssignmentStatement
Anassignmentstatementassignsavaluetoavariable:
=
Aftertheassignmentstatement,thevariable referstothevalueoftheonthe
rightsideoftheassignment.An isanyPythonconstructthathasavalue.
MultipleAssignment
Wecanputmorethanonenameontheleftsideofanassignmentstatement,andacorresponding
numberofexpressionsontherightside:
,,...=,,...
Alloftheexpressionsontherightsideareevaluatedfirst.Then,eachnameontheleftsideisassigned
toreferencethevalueofthecorrespondingexpressionontherightside.Thisishandyforswapping
variablevalues.Forexample,
s,t=t,s
wouldswapthevaluesofsandtsoaftertheassignmentstatement snowreferstothepreviousvalue
oft,andtreferstothepreviousvalueof s.
Note:whatisreallygoingonhereisabitdifferent.Themultiplevaluesarepackedinatuple(whichissimilartothelistdatatypeintroducedinUnit3,butanimmutableversionofalist),
andthenunpackedintoitscomponentswhentherearemultiplenamesontheleftside.This
distinctionisnotimportantforwhatwedoincs101,butdoesbecomeimportantinsome
contexts.
-
8/2/2019 Unit 5 Python Reference
3/11
Procedures
Aproceduretakesinputsandproducesoutputs.Itisanabstractionthatprovidesawaytousethesame
codetooperateondifferentdatabypassinginthatdataasitsinputs.
Definingaprocedure:
def():
Thearetheinputstotheprocedure.Thereisone foreachinputinorder,
separatedbycommas.Therecanbeanynumberofparameters(includingnone).
Toproduceoutputs:
return,,
Therecanbeanynumberofexpressionsfollowingthereturn(includingnone,inwhichcasetheoutput
oftheprocedureisthespecialvalue None).
Usingaprocedure:
(,,)
Thenumberofinputsmustmatchthenumberofparameters.Thevalueofeachinputisassignedtothe
valueofeachparameternameinorder,andthentheblockisevaluated.
-
8/2/2019 Unit 5 Python Reference
4/11
IfStatements
Theifstatementprovidesawaytocontrolwhatcodeexecutesbasedontheresultofatestexpression.
if:
ThecodeinonlyexecutesifthehasaTruevalue.
Alternateclauses.Wecanuseanelseclauseinanifstatementtoprovidecodethatwillrunwhenthe
hasaFalsevalue.
if:
else:
LogicalOperators
Theandandoroperatorsbehavesimilarlytologicalconjunction(and)anddisjunction(or).The
importantpropertytheyhavewhichisdifferentfromotheroperatorsisthatthesecondoperand
expressionisevaluatedonlywhennecessary.
and
IfExpression1hasaFalsevalue,theresultisFalseandExpression2isnotevaluated(so
evenifitwouldproduceanerroritdoesnotmatter).If Expression1hasaTruevalue,
theresultoftheandisthevalueofExpression2.
or
IfExpression1hasaTruevalue,theresultisTrueandExpression2isnotevaluated(so
evenifitwouldproduceanerroritdoesnotmatter).If Expression1hasaFalsevalue,
theresultoftheoristhevalueofExpression2.
-
8/2/2019 Unit 5 Python Reference
5/11
WhileLoops
Awhileloopprovidesawaytokeepexecutingablockofcodeaslongasatestexpressionis True.
while:
IftheevaluatestoFalse,thewhileloopisdoneandexecutioncontinueswiththe
followingstatement.IftheevaluatestoTrue,theisexecuted.Then,theloop
repeats,returningtotheandcontinuingtoevaluatethe aslongasthe
isTrue.
BreakStatement
Abreakstatementintheofawhileloop,jumpsoutofthecontainingwhileloop,continuing
executionatthefollowingstatement.
break
ForLoops
Aforloopprovidesawaytoexecuteablockonceforeachelementofacollection: forin:
Theloopgoesthrougheachelementofthecollection,assigningthatelementtothe and
evaluatingthe.ThecollectioncouldbeaString,inwhichcasetheelementsarethecharacters
ofastring;aList,inwhichcasetheelementsaretheelementsofthelist;aDictionary,inwhichcasethe
elementsarethekeysinthedictionary;ormanyothertypesinPythonthatrepresentcollectionsof
objects.
-
8/2/2019 Unit 5 Python Reference
6/11
Strings
Astringissequenceofcharacterssurroundedbyquotes.Thequotescanbeeithersingleordouble
quotes,butthequotesatbothendsofthestringmustbethesametype.Herearesomeexamplesof
stringsinPython:
"silly"
'string'
"I'mavalidstring,evenwithasinglequoteinthemiddle!"
StringConcatenation
Wecanusethe+operatoronstrings,butithasadifferentmeaningthanwhenitisusedonnumbers.
stringconcatenation: +
outputstheconcatenationofthetwoinputstrings(pastingthestringtogetherwithnospace
betweenthem)
Wecanalsousethemultiplicationoperatoronstrings:
stringmultiplication: *
outputsastringthatiscopiesoftheinputpastedtogether
IndexingStrings
Theindexingoperatorprovidesawaytoextractsubsequencesofcharactersfromastring.
stringindexing:[]
outputsasingle-characterstringcontainingthecharacteratposition oftheinput.Positionsinthestringarecountedstartingfrom 0,sos[1]wouldoutputthesecond
characterins.Iftheisnegative,positionsarecountedfromtheendofthestring:
s[-1]isthelastcharacterin s.
stringextraction: [:]
outputsastringthatisthesubsequenceoftheinputstringstartingfromposition
andendingjustbeforeposition< StopNumber>.Ifismissing,
startsfromthebeginningoftheinputstring;if< StopNumber>ismissing,goestotheendofthe
inputstring.
Length
length: len()
Outputsthenumberofcharactersin
-
8/2/2019 Unit 5 Python Reference
7/11
find
Thefindmethodprovidesawaytofindsub-sequencesofcharactersinstrings.
find: .find()
outputsanumbergivingthepositioninwherefirstappears.If
thereisnooccurrenceofin,outputs-1.
Tofindlateroccurrences,wecanalsopassinanumbertofind:
findafter: .find(,)
outputsanumbergivingthepositioninwherefirstappearsthat
isatorafterthepositiongiveby< StartNumber>.Ifthereisnooccurrenceof< TargetString>in
atorafter,outputs-1.
ConvertingbetweenNumbersandStrings
str: str()
outputsastringthatrepresentstheinputnumber.Forexample, str(23)outputsthestring '23'.
ord: ord()
outputsthenumbercorrespondingtotheinputstring.
chr: chr()
outputstheone-characterstringcorrespondingtothenumberinput.Thisfunctionisthe
inverseoford:chr(ord())= foranyone-characterstring .
SplittingStrings
split: .split()[,,]
outputsalistofstringsthatare(roughly)thewordscontainedintheinputstring.Thewords
aredeterminedbywhitespace(eitherspaces,tabs,ornewlines)inthestring.(Wedidnotcover
thisinclass,butsplitcanalsobeusedwithanoptionalinputthatisalistoftheseparator
characters,andasecondoptionalinputthatcontrolsthemaximumnumberofelementsinthe
outputlist.)
LoopingthroughStrings
Aforloopprovidesawaytoexecuteablockonceforeachcharacterinastring(justlikeloopingthroughtheelementsofalist): forin:
Theloopgoesthrougheachcharacterofthestringinturn,assigningthatelementtothe and
evaluatingthe.
-
8/2/2019 Unit 5 Python Reference
8/11
Lists
Alistisamutablecollectionofobjects.Theelementsinalistcanbeofanytype,includingotherlists.
Constructingalist.Alistisasequenceofzeroormoreelements,surroundedbysquarebrackets:
[,,]
Selectingelements: []
Outputsthevalueoftheelementin< List>atposition.Elementsareindexedstarting
from0.
Selectingsub-sequences: [:]
Outputsasub-sequenceof< List>startingfromposition< Start>,upto(butnotincluding)
position.
Update: []=
Modifiesthevalueoftheelementin< List>atpositiontobe.
Length: len()
Outputsthenumberof(top-level)elementsin.
Append: .append() Mutatesbyaddingtotheendofthelist.
Concatenation: +
Outputsanewlistthatistheelementsoffollowedbytheelementsof< List2>.
Popping: .pop()
Mutatesbyremovingitslastelement.Outputsthevalueofthatelement.Ifthereareno
elementsin,[].pop()producesanerror. Finding: .index()
Outputsthepositionofthefirstoccurrenceofanelementmatching< Value>in.If
isnotfoundin,producesanerror. Membership: in
OutputsTrueifoccursin.Otherwise,outputsFalse.
Non-membership: notin
OutputsFalseifoccursin.Otherwise,outputsTrue. LoopsonLists
AforloopprovidesawaytoexecuteablockonceforeachelementofaList: forin:
-
8/2/2019 Unit 5 Python Reference
9/11
Dictionaries
ADictionaryprovidesamappingbetweenkeys,whichcanbevaluesofanyimmutabletype,andvalues,
whichcanbeanyvalue.BecauseaDictionaryisimplementedusingahashtable,thetimetolookupa
valuedoesnotincrease(significantly)evenwhenthenumberofkeysincreases.
ConstructingaDictionary.ADictionaryisasetofzeroormorekey-valuepairs,surroundedbysquiggly
braces:
{:,:,}
Lookingupelements: []
outputsthevalueassociatedwithinthe.Producesanerroriftheis
notakeyinthe.
Updatingelements: []=
updatesthevalueassociatedwithinthetobe.Ifisalreadya
keyin,replacesthevalueassociatedwith;ifnot,addsanew:pairtothe.
Membership: in
outputsTrueifisakeyin,Falseotherwise.
LoopsonDictionaries
AforloopprovidesawaytoexecuteablockonceforeachkeyinaDictionary: forin:
-
8/2/2019 Unit 5 Python Reference
10/11
Eval
TheevalfunctionprovidesawaytoevaluateaninputstringasaPythonexpression:
eval()
TheinputisastringthatisaPythonexpression;thevalueisthevaluethatstringwouldevaluatetoinPython.
Time
Thetimelibraryprovidesfunctionsforobtainingandmeasuringtime.
importtime
Systemtime: time.clock()
outputstheprocessortimeinseconds(arealnumber,includingfractionalsecondswithlimited
accuracy)(Notethatwhatclockmeansdependsonyourplatform,anditmaynotprovide
accuratetimingsonallplatforms.)
Exceptions
(WeintroducedexceptionsinUnit4becauseweneededtheminourget_pageprocedure,but
youarenotexpectedtounderstandthisindetailorbeabletouseexceptionhandlersinyour
owncodeincs101.)
try:
except:
Executethecodeinthe.Ifitcompletesnormally,skiptheand
continuewiththefollowingstatement.Ifcodeintheraisesanerror,jumptothe
codeinthe.
Theexceptcanbefollowedbyanexceptiontypeandavariablename:
except,:
-
8/2/2019 Unit 5 Python Reference
11/11
Iftheexceptionraisedinthematchesthetype,evaluatethe
withthevariablereferringtotheexceptionobject.
Libraries
import
ImportstheintothePythonenvironment,enablingthefollowingcodetousethe
definitionsprovidedinthe.Pythonprovidesmanylibrariessuchasurllibthatweuse
fordownloadingwebpagesinget_page,andyoucanalsoimportyourowncode.Asprograms
getlarger,itisimportanttoorganizethemwellintoseparatefiles.