Lesson 1

Transcription

Lesson 1
Who am I?
Who areyou?
•
•
•
•
•
•
•
•
•
•
It’sfree
It’sObjectOriented
– Itsupports withaeasysyntaxPolymorphism andInheritance.
It’sPortable
– Youcanexecutethesamecodeoneveryplatform,provided withthePythoninterpreter.
It’ssimple
Ithasalotoflibraries
– Python comeswithalargecollection ofprebuilt andportablefunctionality, knownasthestandard
library.Inaddition, Pythoncanbeextendedwithbothhomegrownlibrariesandavastcollectionof
third-partyapplicationsupport software.
It’sfast!
– Python isaninterpretedlanguage,buthasanintermediatebytecode thatspeedsuptheexecution.
IthastheGarbageCollection
– Youdonothavetomanuallyallocateandfreethememory.
It’seasytouseitasacustomizationandextension tool,thankstoavarietyofintegrationmechanisms
Ithasmanyareasofapplication
– GUIprogramming
• TKinter,PyQt,wxPython
– WebDeveloping
• Django,Web2py
– GoogleAppEngine
– Networkprogramming
• Twisted
– DatabaseinteractionwithODBC
– Gamesdeveloping
• Pygame,pykyra
– Scientificprogramming
• Numpy,Scypy
WHY are you
here?
It’swidely used
–
–
NASA,Yahoo!,Google,Youtube,RedHat,
OpenStack it’swritteninPython
This is basically thetype ofslides that you will get here.
Aquick introduction
Theinterpreter
•
Aninterpreter it’s asoftwareapplication that runs other programs.When
you write acommand inthePython shell,orwhen you run aPython
script,thePython interpreter reads your codeandexecutes the
instructions:you canimagine it as alogical layer between thecodeand
thehardware.
•
Python writes aintermediatebyte-code,that is a"native" Python
command list,tobeexecuted inthePython VirtualMachine.
•
Python is installed onevery Linuxdistribution andonAppleOSX.If you
want aWindowsinterpreter you canget it from:
http://www.python.org
•
WithPython is quite easytowrite codethat does not depend fromthe
machineoperating system:you canwrite thecodeonyour Linuxserver,
andthan copyit ontheWindowsdesktop.(orviceversa)
Programexecution
• Howdoes thecodeexecution workinPython?ThePython scripts
areinterpreted intwo stages:
1.
2.
Afirststagecompiles thetextcodeinbyte-code,alow-level binary
format,that is platform independent.Thebytecodeis stored in.pyc
files:these files will bedirectly loaded when thescriptis executed
multipletimes.
ThePython VirtualMachine,anintermediatesoftwarelayer,runs the
byte-code
• There is not a«make»phase that translates thetextcodein
binary machinecode.
1.
2.
PROS:Thecodeis highly portable,andit is possible torun codefrom
aninteractive shell.
CONS:Theexecution cannot have thesame speed that canbereached
withacompiled code.
IDLEstarts asimple visual editor.
Python CLIstarts aninteractive sessionwiththeinterpreter.
What does it mean towrite aPython program? All you have todois write thePython
instructions inatextfile,preferably withtheestension .py,andthen execute it inthe
Python interpreter.
•
WithIDLEyou canwrite your codeandtestit inthePython shell.
•
You caninputyour codeafter thePython shell prompt,the"triple chevron">>>
•
Theshell executes thecodeimmediately,andshowstheresults onthescreen.
•
IDLE"knows" thePython syntax andfunctions,soit’s able togive you anhint when you useabuiltinfunction,oringeneral afunction that is available inthecurrent namespace.
ForExample: if you write
isinstance(
you cansee that IDLEgives you thefunction arguments inatooltip.
IDLE
• IDLEcolours automatically thecodetext.Defaultis greenfor
strings,orange forlanguage keywords,purple forbuilt-infunctions.
You canofcourse change all thedefaultsettings.
• IDLEhas anautomatic codeindentation,andthat canbeVERY
useful inacomplex code,given thefact that inPython the
indentation is apartofthelanguage.
• If you starttotype acommand,pressingtheTAB key you canhave
hints forits completion,as inbash shell.Check with:
isin+TAB
• IDLEmantains acommand history:withAlt-P (Previous)you can
recall thecodeexecuted,withAlt-N (Next)you canbrowse the
history forward.You canalso modify therecalled code.
PLEASEnotethat Python uses CODEINDENTATION togroup codethat arelogical correlated,as
functions,if statements,forloops,while loops,andsoforth.
Indenting acodelinestarts ablock andunindenting ends it,there arenoexplicit braces,
brackets,orkeywords.Theindentation level ofyour statements is significant,andallow you to
nest codeblocks.
Theexact amount ofindentation doesn't matter at all,Pythons cares about therelative
indentation ofnested blocks (relativetoeach other).
DONOTtomixtabs andspaces forindentation.If you usetabs only orspaces only,you're fine.
Theprint()function has
been introduced in
Python 3.0in
substitution ofthe
homonym keyword
Scripts
• TheIDLEshell canbeused also towrite Python scripts.Ascript,ora
Python program,is atextfilethat contains Python instructions to
beexecuted foraspecific purpose.
• WithFile->New you canopenanewwindow inwhich is possible to
write thescript.Thescriptmustbesaved before being executed.
• WithFile->Openyou canopenandmodify aalready saved script
• If you want torun thescript,you canuseRun->Run Module onthe
menuofthewindow that contains it.
AdvancedIDLE
• FromtheDebug menuyou canenable thebuilt-indebugger
• Adebug sessionis started when
– thedebug is enabled andthen
– theloaded scriptis executed fromRun->Run module.
• You canenable abreakpoint witharightclickonthecode.
• Forfastdebug it is possible tojump fromtheerror message,witha
rightclick,tothecodelinethat originated it.
• OntheLinuxdistributions adedicated debugger,pdb,is also
available.
Let's startwiththelanguage
•
Therearefourbuilt-innumerictypes:
1. integers
int: 0, 1, -3 (C long int)
They have at least 32bitprecision
2. Longintegers
long:0L, 1L, -3L.
May have arbitrary length, their limit depends on theamount ofmemory in
themachine.
3. Double precision real
double)
float: 0., .1, -0.0165, 1.89E+14 (C
4. Double precision complex complex: 0j, 1+.5j, -3.14-2j
•
Informationontheaccuracy andinternal representation offloating point
forthemachineonwhich you're running ascriptareavailable in
sys.float_info
None
•
PythonhasaBoolean typebool,thatcantakethevaluesTrue orFalse,respectively
interchangeable with1and0.
•
There is aspecial variable None (casesensitive),that identifies a“null object”.It is convenient touseit
when you have avariable name but not its value,sothevalue is undefined:
answer
= None
answer
= None
#some
updates…
#some
updates…
answer
None:
ifif
answer
is is
None:
quit=true
quit=true
•
Pay attention tothetest:tocheck if avariable is None always use
if answer is None
if answer is not None
Thecheck if not answer is dangerous,because it is True also if answer is anempty string:
witha = ''; a = []; a= (); a={}; a=0; a=0.0
if a:
#è FALSE
if not a:
#è TRUE
•
Mind theoperator: is checks theidentity ofobjects, == checks if two objects have thesame content
BooleansandStrings
•
Python implements alloftheusualoperatorsforBooleanlogic,butusesEnglish
wordsratherthansymbols(&&, ||,etc.):
t = True
f = False
print type(t)
print t and f
print t or f
print not t
print t != f
•
#
#
#
#
#
Prints "<type 'bool'>"
Logical AND; prints "False"
Logical OR; prints "True"
Logical NOT; prints "False"
Logical XOR; prints "True"
Python has great support forstrings:
hello = 'hello'
#
world = "world"
#
print hello
#
print len(hello)
#
hw = hello + ' ' + world
#
print hw
#
hw12 = '%s %s %d' % (hello, world, 12) #
print hw12
#
•
String can use single quotes
or double quotes
Prints "hello"
String length; prints "5"
String concatenation
prints "hello world"
sprintf style string formatting
prints "hello world 12""
Python includes several built-in containertypes:lists,dictionaries, sets,andtuples.
Python lists
Let’s startfromdata
• Almost every serious program works withdata!
• Sometimes thedataarevery simple,andit’s easytowork
withthem.Sometimes they have acomplex structure,and
thecodethat mustuseandmodify them canbecome quite
involved.
• Often it canbeuseful toaccomodatethedatainalist,that
expressalogical connectionbetween them:aclientslist,
your friendslist,theto-dolist,alistoftimerecords,etc..
• Forsuch acommontaskPython has adedicatedatatype:
list
Anexample
Let’s suppose that our problem dataarethefollowing:
Isolitiignoti, 1958,MarioMonicelli, 102mins
Antonio DeCurtis
VittorioGassman, MarcelloMastroianni, RenatoSalvatori,ClaudiaCardinale
Iduemarescialli,1961,Sergio Corbucci,99mins
Antonio DeCurtis
VittorioDeSica,GianniAgus, Arturo Bragaglia,MarioCastellani
Uccellaccieuccellini, 1966,PierPaoloPasolini, 85mins
Antonio deCurtis
NinettoDavoli,FemiBenussi,GabrieleBaldini
Atafirstglance you cansee that we have acomplex list,but withaninternal structure:each
recordcorresponds toafilm,thefirstlinecontains somebasic informations,thesecond line
contains thename oftheprotagonist,thethird one contains thenames ofsomeothers actors
http://bit.do/ListaFilm-txt
Anexample
Let’s startfrom thetitles list:
I soliti ignoti
I due Marescialli
Uccellacci e uccellini
andlet’s write it inPython
>>> film = ["I soliti ignoti", "I due Marescialli", "Uccellacci e
uccellini"]
Howdid we make thetranslation?
1. Each linehas been trasformed inastring,using doublequote"
2. Each listitemis separated from thenext byacomma,
3. Thelistitems arewritten between square brackets []
4. Thelistis assigned toanidentifier (film )withtheassignment operator =
Dynamic Typing
• But…aminotsupposedtodeclare,somewhere before,ofWHICH
TYPEistheidentifierfilm?
• No,because Python is a"dynamically typed" language:you can
useanewvariable without before declare its type.
InPython avariable identifier is asimple name that refers toan
object,whatever is thetype ofthat object.
a=[1,2,3]
a
123
• Beaware that although dynamic,thetyping inPython is "strong",
soyou cannot merrily add floatandstring forexample…
Lists items
• When you createalisttheinterpreter creates anewmemory
structure,similar toavector.Thefirstelement has ALWAYSthe
index 0,thesecond 1,thethird 2andsoon.
• Withthese indices,automatically assigned,it is possible todirectly
address thelistitems,withthenotation:
>>> print film[1]
I soliti ignoti
• Although this vector similarity,Python lists aresomething more.A
listis acollection object,soit has abunch ofpre-defined functions
ormethods available.
Example:lists operations
>>> classe = ["Anna", 'Giulia', 'Vito', "Michele"] len is aBuilt-InFunction(BIF)
>>> print classe
append it’s amethod oflist
['Anna', 'Giulia', 'Vito', 'Michele']
objects that adds anitemtotheend
>>> print len(classe)
ofthelist
4
>>> print classe[2]
popRemoves theitemat thegiven
Vito
positioninthelist,andreturns it
>>> classe.append("Rosa")
extend Extends thelistby
>>> print classe
['Anna', 'Giulia', 'Vito', 'Michele', 'Rosa'] appending all theitems inthegiven
>>> classe.pop()
list
'Rosa'
Remove(x) Removes thefirst
>>> classe.extend(["Rosa",'Gioacchino'])
itemfromthelistwhose value is x.
>>> print classe
['Anna', 'Giulia', 'Vito', 'Michele', 'Rosa', 'Gioacchino']
>>> classe.remove('Vito')
>>> print classe
insert Inserts anitemat agiven
['Anna', 'Giulia', 'Michele', 'Rosa', 'Gioacchino']
position.Thefirstargument is the
>>> classe.insert(0, 'Maurizio')
index oftheelement before which
>>> classe.insert(0, 'Vito')
toinsert
>>> classe.insert(0, 'Elio')
>>> print classe
['Elio,'Vito','Maurizio','Anna', 'Giulia', 'Michele', 'Rosa', 'Gioacchino']
Let’s add other data
I soliti ignoti, 1958, Mario Monicelli, 102 mins
Antonio De Curtis
Vittorio Gassman, Marcello Mastroianni, Renato Salvatori, Claudia Cardinale
I due marescialli, 1961, Sergio Corbucci, 99 mins
Antonio De Curtis
Vittorio De Sica, Gianni Agus, Arturo Bragaglia, Mario Castellani
Uccellacci e uccellini, 1966, Pier Paolo Pasolini, 85 mins
Antonio de Curtis
Ninetto Davoli, Femi Benussi, Gabriele Baldini
This is our initial list:
>>> film = ["I soliti ignoti", "I due Marescialli", "Uccellacci e
uccellini"]
Now we want toadd theyear of production, using themethods oftheprevious slide.
But…
• Is it possible toadd numeric items inalistthat already contains
string items?
• YES:aPython listcancontain objects ofdifferent types.Infact you
candomorethan mixnumbers andstrings:you canstore inalist
dataofany type.
• Thelisthas tobethought ofas asetoflogically related objects :
Python obviously cannot know bywhat logic they arerelated,and
provides justthetool togroup them together,regardless oftype.
• Think about thelistas ahigh-level "collection":thedatatype of
items is not important forthelist.All that Python needs toknow is
that you have created alist,you gave it aname,andinsidethere
aredata.
Usingtheinsertandappend commands,howcanItrasform thelist:
>>> film = ["I soliti ignoti", "I due Marescialli", "Uccellacci e
uccellini"]
Inthefollowing list?
["I soliti ignoti", 1958, "I due Marescialli", 1961, "Uccellacci e
uccellini", 1966]
And howamIsupposed tocreateitfromscratch,asitisinthissecond version?
>>> film.insert(1,1958)
Remember that thefirstparameter is theindex oftheitemBEFOREofwhich the
insertion occurs.
>>> film.insert(3,1961)
Aftertheinitialinsertion thelistexpands, soforthesecondinsertion thenew
elementmustbetakenintoaccount.
>>> film.append(1966)
>>> film = ["I soliti ignoti", 1958, "I due Marescialli", 1961, "Uccellacci
e uccellini", 1966]
Loops andconditions
Working withdata
•
It is often necessary toiteratethrough thelistitems,inorder tobeable toperform
someoperation onthem.
•
Todothis you canuseafor loop . This loop is designed inPython toworkon lists
ORonany other object that Python considers iterable.
•
Aniterable object is acontainercapable ofreturning its items one byone.
Objectsof this type areall objects that have one ofthefollowing functions
defined:
__iter()__
__getitem()__
When aniterable is passed totheBIFiter(),which happens automatically
insideaforloop, it returns aniterator.
•
Aniterator It is anobject that represents adatastream,andenables the
programmer totraversethe container.
•
Inother words,inPython, aniterable is anobject which canbeconverted toan
iterator,which is then iterated through during theforloop;this is done implicitly.
Forloop
for
<target identifier> in <iterable>:
<target processing code>
Thekeywordfor marks thebeginning ofthecycle.
The<target identifier> it’s thevariable name that will contain the
iterable elements.
Thekeywordin separates thetargetname fromtheiterable
Acolon: indicatethestartofthecodethat processes data
ThecodeMUSTbeindented below theforline.
Thetargetidentifier is not previously declared ,andit is similar toany other
name inPython;when thecycle goes on,thelistgives its items tothefor
loop,andeach iteminthelistis assigned tothetarget,one after theother.
Numeric forloop
for
<target identifier> in range(n):
<processing code>
Therange(n) BIFallows torealize acycle that is repetead adefined
number oftimes;it returns aniterable that contains theintegers
ranging from0ton-1
>>> for num in range(4):
print num
InPython 2.7while rangecreatesacompleteiterable,soifyoudo
range(1, 10000000) itcreatesalistinmemorywith9999999
elements,thefunctionxrange(n) isasequenceobjectthat
evaluateslazily.
Listloops
Aloop overall theelements ofalist:
>>> film = ["I soliti ignoti", 1958, "I due Marescialli", 1961, "Uccellacci
e uccellini", 1966]
>>> for item in film:
print 'item is ', item
If you mustknow thelocation oftheitemwithin thelist:
>>> film = ["I soliti ignoti", 1958, "I due Marescialli", 1961, "Uccellacci
e uccellini", 1966]
>>> for index in range(len(film)):
print 'film[%d]=%s' % (index, film[index])
Youcaniterateovermultiple listsortuplessimultaneously using thezip function:
>>> for x, y, z in zip(xlist, ylist, zlist)
#work with x,y,z
While loop
What is done withthecode:
>>> film = ["I soliti ignoti", 1958, "I due Marescialli", 1961, "Uccellacci
e uccellini", 1966]
>>> for each_item in film:
print each_item
Canalso bedone withawhile loop:
>>> count = 0
>>> while count < len(film):
print film[count]
count = count + 1
Ifyouareusing awhileloop you havetoworryaboutthe"statusinformation" ,andso
youneedtouseavariablethatallowstoendthecyclewhenthelistisexhausted.
Withtheforloop thisitisnot necessarybecauseeverything ishandled bythePython
interpreter.
while/else- for/else
• Awhile loop canhave anadditional statementelse:
i=0
while i<len(L):
print 'at index', i
i=i+1
else:
print X, ' not found'
Theelsecodeblock is executed when thecondition ofthe
while loop becomes False,also forthefirsttime,then
unless there is abreakintheloop it is always executed.
• Aforstatementcanalso have anelseblock that,unless the
cycle contains abreakinstruction,it is always executed at the
endoftheloop.
Lists oflists
• Wehavealreadyseenthatthelistscancontaindataofanytype,
andalsoofmixedtype:alogicalextensionofthisstatementisthat
theycanalsocontainlists,andindeeditistrue!
Let's return toour example data:
I soliti ignoti, 1958, Mario Monicelli, 102 mins
Antonio De Curtis
Vittorio Gassman, Marcello Mastroianni, Renato Salvatori,
Claudia Cardinale
• We canview this as alistofinformations ona film,which contains
thelistofactors,which contains thelistofsecondary actors.
>>> film = ["I soliti ignoti", 1958, "Mario Monicelli", 102, ["Antonio De
Curtis",
["Vittorio Gassman","Marcello Mastroianni","Renato Salvatori","Claudia
Cardinale"]]]
Lists oflists
•
Nested lists canbemanipulated withtheir listmethods,andyou can
access their datawiththesquare bracket notation already seen.What will
betheresult oftheprint instruction?
0
1
2
3
>>> film = ["I soliti ignoti", 1958, "Mario Monicelli", 102,
0
0
4
1
1
["Antonio De Curtis", ["Vittorio Gassman","Marcello Mastroianni",
2
3
"Renato Salvatori","Claudia Cardinale"]]]
>>> print film[4][1][3]
Claudia Cardinale
•
What happens if we useafor loop toiterateovertheitems ofthis list
containing other lists?Tocheck that you caninsert this listinanIDLE
sessionandtry toprint each element withtheforloop that we saw before
(for each item in list)
Lists oflists
>>> film = ["I soliti ignoti", 1958, "Mario Monicelli", 102, ["Antonio De
Curtis",["Vittorio Gassman","Marcello Mastroianni","Renato
Salvatori","Claudia Cardinale"]]]
>>> print film
['I soliti ignoti', 1958, 'Mario Monicelli', 102, ['Antonio De Curtis',
['Vittorio Gassman', 'Marcello Mastroianni', 'Renato Salvatori', 'Claudia
Cardinale']]]
>>> for each_item in film:
print each_item
I soliti ignoti
1958
Mario Monicelli
102
['Antonio De Curtis', ['Vittorio Gassman', 'Marcello Mastroianni', 'Renato
Salvatori', 'Claudia Cardinale']]
Theforloop prints only theelements of the"primary" list:when it finds thenested
listit does not see any difference (is only another object after all)andit prints thelist.
If you want todo something different, as print theitems ofthenested list,you need to
check whether theitemis alistandact accordingly.
if…elif...else
if
<some condition>:
<TRUE code>
else:
<FALSE code>
Thekeywordif marks thebeginning ofthedecision-making process
Acolon: follows thecondition that mustbemet
Thekeyword elif <other condition>: marks thebeginning of
another condition check
Thekeywordelse: marks thebeginning ofthealternative
Thecodethat processes datamustbeindented underthelines ofif andelse
Thetestif var returns false if var is
1.
2.
3.
4.
5.
6.
7.
None
Thenumber 0
Theboolean False
Anempty string ('')
Anempty list([])
Anampty tupla (())
Anempty dictionary ({})
Comparisons
•
There is asourceofpotential confusion when you doacomparison anddonot pay
attention tonot mixstrings andnumbers.
>>> b='1.2'
>>>b='1.2'
>>>
if b<100:
>>>if print
b<100:
b, '<100'
...
print
b, '<100'
else:
...else:
print b, '>=100'
...
1.2
>= 100 print b, '>=100'
•
You canhave theprevious situationif,forexample,you load sys.argv[1] ina
variable b andpass1.2as thefirstargument ofthecommand-line script.
Herethetestb<100is always FALSE. b is astring, andyou arecomparing it withan
integer.Python does not give any error message.Thecorrect syntax is:
if float(b) < 100:
>>>if float(b) < 100:
>>>if b< str(100):
if b< str(100):
•
Pay attention also totheinteger division! As inmany other languages thedivision
between two integers gives aninteger, which is often not what you want ...
Typecheck
But how canyou check thetype of theobject pointed byagiven name?You canuse
theBIFisinstance().
>>> names = ["Domenico", "Angela"]
>>> isinstance(names, list)
True
>>> num_names = len(names)
>>> isinstance(num_names, list)
False
If you want toknow all theBIF,you canuse:
>>> dir(__builtins__)
Thedir command canbeused tohave alistofall the"strings" attached toa
particular object.
__builtins__ it’s thename ofamodule that contains all theBIFs.Thesame
command canbeused onany object toget informationonits properties.Tofind out
moredetails about asingle function (orany object), you canusethehelp command,
orinvoke aninteractive sessionwithhelp()
>>> help(isinstance)
Application
This is our standardcodethat print every listitem,without type checking
>>> film = ["I soliti ignoti", 1958, "Mario Monicelli", 102, ["Antonio De
Curtis",["Vittorio Gassman","Marcello Mastroianni","Renato Salvatori",
"Claudia Cardinale"]]]
>>> for each_item in film:
print each_item
Now we canmodify it toprint thenested lists items.
Processes theinitial list
>>> for each_item in film:
if isinstance(each_item, list):
for nested_item in each_item:
print nested_item
else:
print each_item
This could beafirstapproximation.
What is its fault?
If it is alist,print its content
withanewtarget
Correction
Intheexample there arethree levels ofnested lists.You mustthen re-modify thecode
toinclude thethird level.
>>> for each_item in film:
if isinstance(each_item, list):
for nested_item in each_item:
print nested_item
if isinstance(nested_item, list):
for deeper_item in nested_item:
print deeper_item
else:
print nested_item
else:
print each_item
But ...what if we want tomodify thedataandadd another nested level?
We should modify thecodeagain,andmake it increasingly complicated tomanage ...
Now it’s timetointroduce thefunctions
Functions,variables,
assignments
Functions
>>> for each_item in film:
if isinstance(each_item, list):
for nested_item in each_item:
if isinstance(nested_item, list):
for deeper_item in nested_item:
print deeper_item
else:
print nested_item
else:
print each_item
Same “forloop”
Intheprint loop alot ofcodeis repeated.Inthese cases it is advisable totry to
identify thecommonbehavior, andincludeit inone reusable function, toimprove the
readability ofthecodeandits maintenance.
Functions
InPython,afunction is anormal block ofcode,which canalso have input
arguments.
You define afunction using thekeyworddef,providing aname forthe
function andspecifying alist,even empty,ofinputarguments inparentheses
def
<function name>(<argument(s)):
<function code>
Theparentheses aremandatory,unlike thearguments.Thecodeofthe
function mustbeindented as usual
It does not exist inPython,unlike what happens inC++,theconcept of
"function overloading":thenumber,name ortype ofarguments cannot be
used todistinguish between two functions withthesame name,then the
name uniquely identifies thefunction.
Usually thefunctions aregrouped into modules.
Backtotheexample
Thefunction that we need musttakealistas input, andprocess every item.If theitem
is not alist,it mustprint it.If theitemis alist,thefunction mustcallanother copyof
itself,withtheexamined itemas argument.
Sowhat we need is arecursivefunction,namely afunction that calls itself within its
own code.
Say that thefunction is called print_lol (),andit takes one argument, thelistthat it
mustprint onthescreen.Howcould you completethefollowing code?
>>>
>>> def
def print_lol(the_list):
print_lol(the_list):
for
the_list:
for each_item in :
if
list):
if isinstance(each_item,
:
print_lol(each_item)
else
else :
:
print each_item
As you have noticed thecodesize has been reduced, thecomprehensibility is
increased andtherefore themaintenance ofthecodehas become much simpler.
And now,even though inthedataappears anewlevel ofnested list,there is noneed
tochange theprocessing code.
Python variables
•
InPython when you assign avariable you aremaking sure that aREFERENCE
toanOBJECThas aNAMEwhich identifies it.Anassignment then creates a
reference,orapointer toamemory area,andaname.
•
Avariable name does not has anintrinsic type assigned (as inCint i).
Thetype is intheOBJECTS,andPython automatically determines thetype of
thereference (thevariable)based onthetype ofdatareferenced.
•
Areference is created thefirsttimethat appears totheleft ofanassignment
expression:
>>> x=3
•
Thereference is then deleted bythegarbage collector after each name
attached toit results unused,andanobject is deleted if there arenomore
references pointing toit.
•
Thevariables mustbeassigned before they areused inthecode.
What happens when you createa
variable?
>>> y=5
1.
2.
3.
4.
5.
name
yy
pointer
object
5
Firstofall,aninteger 5 it's created andplaced inmemory
Thename y is created
Thename yis assigned toareference tothememory location that
contains thenewnumber 5
Now when we say that "thevalue ofy is 5" we mean that thename y is
assigned toareference that points towards amemory location,which
contains theobject 5
Theobject 5 that we have created is aninteger.Python datatypes int,
float,andstring arecalled "immutable".This does NOTmean ofcourse
that we cannot change y,we cansafely change theobject towards it
points:
Assignment
>>> y += 1
>>> print y
6
y
What happens when thevalue ofyis increased by1?
Python…
1.
2.
3.
4.
5.
5
6
…searchs thepointer whose name is y.
…retrievesthevalue(5)oftheobjecttowhichthereferencepoints
…computes thesum5+1,generates anew integer object 6inanew memory
location
…assignsthenameytoareference towards thenewmemory location
…deletestheold memory location(5), iftherearenopointersleftpointing
atit.
Immutable assignment between
variables
•
>>>
>>>
>>>
>>>
3
x=3
y=x
x=4
print y
#creates 3, x points to 3
#creates the name y, that points to 3
#creates 4, x now points to 4
#y points yet to 3
• When you modify thedatax,you change thereference,but you do
NOTtouch thereference named y.Everything is OK…
• But inPython there areother datatypes that aremutable,or
changeable:lists,dictionaries,anduser defined class datatypes
Mutable assignment between
variables
• Themutable datais modified directly without changing the
memory locationinwhich they arehoused.
>>> a=[1,2,3]
>>> b=a
>>> a.append(4)
>>> print b
[1,2,3,4]
#a points to the list[1,2,3]
#b point to the same list object
#this modifies the list object
#b is also changed
• Tosee if two names point tothesame object,you canusetheis
operator,which compares objects;You canalso usetheid
operatortohave theexplicit object's unique numeric identifier.
• This behaviour strongly influences theuseoffunctions input
variables.
Intuition
a=[1,2,3]
b=a
a
123
a
b
123
a
a.append(4)
b
1234
Functionsandvariables
CallbyValue
CallbyReference
Copy
DuplicateCopyofOriginal
ParameterisPassed
ActualCopyofOriginal
ParameterisPassed
Modification
NoeffectonOriginal
Parameteraftermodifying
parameterinfunction
OriginalParametergets
affectedifvalueof
parameterchangedinside
function
CandC++usebydefaultthe"callbyvalue" schema,bymaking acopyof thevariables
within thefunction, but you canusepointers andget the"callbyreference".
This lastbehaviour is standardinFortran.
Sowhat happens inPython?
Functions andinputvariables
• Python functions argument passing is asort of«callby
assignment»,inthesense that anassignment operatoris
applied between theargument andthevariable used inthe
call.
• Concretely: theinputfunction parameters arepassed with
a«callbyreference»(pointer),if thedatatype is mutable,
witha«callbyvalue»(copy)if thedatatype is immutable.
• It is then agood practice toalways return every parameter
modified insidethefunction.Notethat withasinglereturn
statementyou canreturn any number ofvariables.
Example
>>> def change1(some_list):
some_list[1] = 4
>>> x = [1,2,3]
>>> change1(x)
>>> print x
Whatisthevalueofx?
x = [1,4,3]
>>> def change2(x):
x = 0
>>> y = 1
>>> change2(y)
>>> print y
Whatisthevalueofy?
y = 1
Sharedreferences
>>> x = [1,2,3]
>>> L = ['A',x,'C']
>>> L
['A', [1,2,3], 'C']
>>> x[1] = 'sorpresa!'
>>> L
['A', [1,'sorpresa!',2], 'C']
Thechange intheobjectpointed byxisvisiblefrom everyreferencethatpointtothe
sameobject.
L
A
C
x
1
?
3
Copy
But then how is it possible tomake asimple copy?
>>> list2=list1
Thetwo names have thesame reference tothesame object.Achange inone ofthe
lists influences also thesecond list
>>> list2=list1[:]
Herelist1andlist2aretwo independent copies,two references totwo different
objects
>>> list2=[]
Createanempty list,useful if you want tofill it insideaprocessing code.
Listslicing
1.
Thestarting index is always included,thefinal index is always
excluded.
2.
If you assign avalue toaslice you change theoriginal listonsite.
3.
If you assign aslice toavariable,you createacopy oftheoriginal list,
withtheindices specified intheslice.
4.
Alwaysremember that thefirstindex is ZERO
0
1
M
[:
2
A
-2
S
T
E
R
B
A
[start:end]
Theindicesindicatewheretheknife“cuts”
-1
R
I
:]
0
1
P
[:
2
H
-2
D
U
N
I
B
A
-1
R
Thestarting index is always included, thefinal index is always excluded
>>> a = 'demonstrate slicing in Python'.split()
>>> print a
['demonstrate', 'slicing', 'in', 'Python']
>>> a[-1]
'Python’
# the last entry
>>> a[:-1]
# everything up to but, not including, the last entry
['demonstrate', 'slicing', 'in']
#Equal to a[0:len(a)-1]
>>> a[:]
# everything
['demonstrate', 'slicing', 'in', 'Python']
>>> a[2:]
# everything from index 2 and upwards
['in', 'Python'] #Equal to a[2:len(a)]
>>> a[-1:]
['Python']
# the last entry
>>> a[-2:]
# the last two entries
['in', 'Python']
I
:]
0
1
P
[:
2
H
-2
D
U
N
I
B
A
Thestarting index is always included, thefinal index is always excluded
-1
R
I
:]
>>> print a
['demonstrate', 'slicing', 'in', 'Python']
>>> a[1:3]
# from index 1 to 3-1=2
['slicing', 'in']
>>> a[:0] = 'here we'.split() # add list in the beginning (to the
# first, not included)
>>> a
['here', 'we', 'demonstrate', 'slicing', 'in', 'Python']
>>> b = [2.0]*6
# create list of 6 entries,each equal 2.0
>>> b
[2.0, 2.0, 2.0, 2.0, 2.0, 2.0]
>>> b[1] = 10
# b[1] becomes the integer 10
>>> c = b[:3]
>>> c
[2.0, 10, 2.0]
>>> c[1] = 20
# is b[1] affected?
>>> b
[2.0, 10, 2.0, 2.0, 2.0, 2.0] # no c is a copy of b[:3] (slicing is a copy)
>>> b[:3] = [-1]
# first three entries replaced by one entry
>>> b
[-1, 2.0, 2.0, 2.0]
tuples
•
Withtheroundbrackets you candefine aspecialtype oflists,tuples:like
lists they areiterables,but withtheparticularity that they areimmutable.
•
Another particular example ofimmutable listis thestring.
•
You cannot change any element ofanimmutable sequence (tuple or
string)without destroying andrecreating it,then changing its memory
location.
•
Atupla canact as aconstant listinthecode.
•
If thetuple contains alist, canyou change thevalues oftheliston-site?
>>> mylist=[1,2,3]
>>> mytupla=(4,mylist,5)
>>> mylist[1]='check’
>>> mytupla
(4, [1, 'check', 3], 5)
>>> mytupla[0]=8
TypeError: 'tuple' object does not support item assignment
Variables assignation fromtuples or
lists
• You canextract theitems oflists andtuples inseparatevariables,withthe
following syntax (here arglist is alistortuple ofthree items):
>>> [filename, plottitle, psfile] = arglist
>>> (filename, plottitle, psfile) = arglist
>>> filename, plottitle, psfile = arglist
• If ontheleft there is ONEvariable,then we have alistassignment,if there
arethree variables we assign thelistitems tothevariables,but if there
aretwo,orfour ormorevariables we have anerror.
• Thein operatorcanbeused toverify if alistcontains aspecific item:
>>> list=['a','b','c']
>>> var='c'
>>> if var in list:
print 'Eureka!'
It canbeused also intheforloops.
Codeexecution model
• Python executes thecodefromthebeginning ofthe
module orscriptlinearly towards theend.
• References arecreated when they areprocessed:wrong
codethat it’s not processed does not give any error ( "Ifit's
nottested,it'sbroken.")
>>> x = 3
>>> if x > 5:
show config()
Thefunction is NEVERcalled:we donot have error
>>> show_version()
>>> def show_version():
print 'Version 1.0a'
This codegives error:you cannot use thefunction
show_version() before its definition.
>>> def test():
show_version()
>>> def show_version():
print 'Version 1.0a'
>>> test()
This codeis ok:when test() is executed the
show_version() function is alredy defined
and/or
1. X or Y
If Xis False,returns Y(that canbeTrue orFalse),elsereturns X
2. X and Y
If Xis False,returns X,elseY
3. not X
If Xis False,returns True,elseFalse
•
Theandandoroperators are"shortcircuits",inthesense that
– or evaluates thesecond argument only if thefirstis False
– and evaluates thesecond argument only if thefirstis True
•
not has lower priority than non-boolean operators,so
not a==b
is interpreted as
not (a==b)
Shortcircuit
•
Theoperator
x and y (shortcircuit and)
is equivalent to
if x then y else False
•
Theoperator
x or y (shortcircuit or)
is equivalent to
if x then True else y
•
There aretwo essential practical applications,think forexample totheAND:
1.
2.
•
Thefirstexpression checks theneed forintensivecomputation, which is
performed inthesecond expression
Thefirstexpression ensures theoccurrence ofacondition necessary tothe
calculation ofthesecond espression
Ther might also besomeproblems:
–
If thesecond expression is afunction that mustperform operations that are
expected independently from thefirstexpression