INTRODUCTORY COURSE TO PRACTICAL PYTHON PROGRAMMING
Engku Ahmad Faisal
[email protected] github.com/efaisal twitter.com/efaisal facebook.com/eafaisal plus.google.com/1000858!!"8!#551
ABOUT THIS COURSE ●
Fundamental course on programming and $%thon
●
da%s
●
Format&
●
●
–
'ectures
–
(ands)on e*ercises
–
(andout
Feel free to ask +uestion an%time Alwa%s use the official $%thon documentation ,https&//docs.p%thon.org/-/ ,https&//docs.p%th on.org/-/ or https&//docs.p%tho https&//docs.p%thon.org// n.org//
INTRODUCING PROGRAMMING What is Programming? ●
●
●
nstruction to do something to achiee a desired result sing series of steps or actions that a programmer defines ,procedure Each action works on certain ob2ect,s or data in order to attain a well defined goal
REAL WORLD EAMPLE O! PROGRAMMING Sham"oo Instr#$tion ●
3ash
●
4inse
●
4epeat
o %ou notice the problem with the instruction6
COMPUTER PROGRAMMING
●
●
●
7omputer is a dumb deice that cannot understand human language ou9 as a programmer9 need to tell the computer precisel% what to do se programming language which helps to translate %our instruction so that computer can understand
WHAT IS PYTHON? An O%&r%i&' ●
●
●
A high leel9 general purpose programming language (igh leel& don:t need to know the details of hardware ;eneral purpose& can be used to build man% kind of application applications s ,s domain specific language such as (<='9 >?'9 =A<'A
WHAT IS PYTHON? ($ont) A *itt*& histor+, ●
esigned b% ;uido an 4ossum
●
First release in 11
●
●
(as man% implementatio implementation& n& 7$%thon9 $%$%9 B%thon9 ron$%thon 3e:ll be using the reference implementation&& 7$%thon implementation
WHAT IS PYTHON? ($ont) Wh+ *&arn P+thon? ●
'ow learning cure
●
CEnforceD good programming practice
●
=ulti)platforms&& 3indows9 'inu*9 =ac =ulti)platforms
●
CatteriesD included
WHAT IS PYTHON? ($ont) E-am"*&s o. a""*i$ations that $an /& /#i*t #sing P+thon, ●
esktop applicati applications/games ons/games
●
3eb)based applications
●
●
>%stem administrator tasks automation >cientific engineering data anal%sis
WHAT IS PYTHON? ($ont) Who #s&s P+thon? ●
●
;iant companies goernment agencies& –
;oogle9 ropbo*9 nstagram
–
7E49 A>A
n =ala%sia& –
●
<=9 7EF9 >tar ewspaper
ouG ownload from www.p%thon.org
INTRODUCING IDLE
●
'E is an integrated deelopment enironment
●
$art of $%thon standard librar% using
●
$roides $%thon shell and a te*t editor
●
ot great but good enough for our purpose
0ALUE 1 EPRESSION
●
●
●
●
●
<%pe on the $%thon shell& HHH 1 I As e*pected the result is
STORING 0ALUE
●
>tore into ariable
●
sing the J sign
●
E*amples& HHH ar J HHH ar HHH a J 1 HHH ar I a HHH result J ar I a HHH result
DATATYPES, NUMBERS
●
ntegers
●
HHH a J HHH t%pe,a Kclass :int:H HHH ●
HHH import fractions HHH L >imulate 1/ HHH c J fractions.Fraction,19 HHH c Fraction,19 HHH
Floats HHH b J -.5 HHH t%pe,b Kclass :float:H HHH
Fractions
●
7omple* numbers
DATATYPES, NUMBERS ($ont) 7ommon Mperators for umbers
2
Addition
4
>ubstraction
35
6
=ultiplication
7
8
iision
9
=odulus ,calculate remainder
3
75
;reater than ;reater than or e+ual to 'esser than 'esser than or e+ual to
PRIMITI0E DATATYPES
DATATYPES, STRINGS
●
Enclosed b% single +uotes HHH :this is a string: :this is a string: HHH
●
Enclosed b% double +uotes HHH Cthis is also a stringD :this is also a string: HHH
●
Enclosed b% triple single or double +uotes for multilines string HHH :::first multi N line string::: :first multiOnline string: HHH CDDsecond multi N line stringDDD :second multiOnline string: HHH
DATATYPES, STRINGS
●
●
7oncatenate HHH a J :m% : HHH a I :string: :m% string: HHH 4epeat HHH b J :ha : HHH b P :ha ha ha : HHH
●
'ong string HHH m%str J ,:put in bracket : N :to handle long string: HHH m%str :put in bracket to handle N :
DATATYPES, STRING
●
>tring is a se+uence of characters can be inde*ed/subscripted HHH m%str J :$%thon: HHH m%strQ0R :$: HHH m%strQ5R :n: HHH m%strQ)1R :n: HHH m%strQ)!R :$:
DATATYPE, STRINGS
●
●
>tring is a se+uence of characters can be sliced HHH m%str J :$%thon: HHH m%strQ1&R :%thon: HHH m%strQ1&5R :%tho: HHH
BASIC DATA STRUCTURE
DATA STRUCTURE, LIST
●
●
●
●
●
=utable ,changeable9 compound ,group of alues data t%pe lank lists HHH a J QR HHH b J list, 'ists with default alues HHH a J Q19 -9 9 #R HHH b J Q:*:9 :%:9 :S:R 'ook at the aailabl aailable e methods to manipulate list 'ist comprehension& a more adance topic on list will be coered later
DATA STRUCTURE, TUPLE
●
●
●
●
mmutable ,unchangeable9 compound ,group of alues data t%pe lank tuples HHH a J , HHH b J tuple,
DATA STRUCTURE, DICTIONARY
●
●
●
=apping datat%pe ,ke%)alueT similar to associatie arra% in some languages lank dictionaries HHH a J UV HHH b J dict, ictionaries with alues HHH a J U:a:& 19 :b:& -V HHH b J dict,,,:a:9 19 ,:b:9 -
CONTROL !LOWS
CONTROL !LOW, I!
●
●
7onditional control flow E*ample ,ote& identation is # spaces& HHH * J 5 HHH if * K 0& N print,:egati print,:egatie e alue: N elif * JJ 0& N print,:Wero: N elif * H 0 and * K 11& N print,:etwee print,:etween n 1 and 10: N else& N print,:=ore than 10: :etween 1 and 10: HHH
CONTROL !LOW, !OR
●
●
terates oer items in iterables ,e.g. list9 tuple E*ample& HHH for n in range,-9 10& N for * in range,-9 n& N if n X * JJ 0& N break N else& N print,n9 :is a prime number: L $%thon N print n9 :is a prime number: L $%thon -
●
break is is used to terminate iteration
●
else is else is e*ecuted if no break occurs occurs in the for iteration iteration
CONTROL !LOW, !OR
●
●
Another e*ample& HHH for i in range,-9 10& N if i X - JJ 0& N print,i9 : is an een number: L $%thon N print i9 : is an een number: L $%thon N continue N print,i9 : is an odd number: L $%thon N print i9 : is an odd number: L $%thon continue ke%word continue ke%word means continues with ne*t iteration
CONTROL !LOW, WHILE
●
●
●
sed to loop or repeat a section of code for as long as the condition ,e*pression ,e*pression defined in the statement is true E*ample9 to loop foreer& HHH while
!UNCTIONS
WHAT IS A !UNCTION?
●
●
●
A named section of a program that performs specific task Allow to organiSe code block which repeatedl% repeatedl% used into a reusable procedure or routine $%thon comes with a lot of built)in functions which we alread% seen some of them
!UNCTION, DE!INING
●
●
●
●
●
sing the ke%word def Followed b% a name9 patentheses ,for possible arguments and a colon od% of a function must be indented Yariables defined in a function is stored in the local s%mbol table =a% return a alue using return ke%word return ke%word
●
E*ample& Fibonacci series HHH def fib,n& N CDDoc stringDDD N a9 b J 09 1 N while a K n& N print a9 L $%N print,a9 endJ: : L $% N a9 b J b9 aIb N print, L $% N HHH fib,-000
!UNCTION, DE!AULT ARGUMENT
●
●
●
●
>ometimes it:s useful to define default alue to argument of a function E*ample& HHH def calculate,a calculate,arg9 rg9 alJ1& N efault alue is ealuated at the point of function definition and ealuated on once E*ample& HHH i J HHH def f,argJi& N HHH i J 5
!UNCTION, :EYWORD ARGUMENT
●
●
Function can be called using ke%word argument E*ample& HHH def func,arg1J19 sa%J:hello:9 sa%J:hello:9 argJ5& N print,sa% N print,arg1 N print,arg HHH func,sa%J:world: L sing ke%word argument HHH func,19 :world: L sing positional arguments HHH func, L sing default arguments HHH
!UNCTION, ARBITRARY ARGUMENT
●
●
!UNCTION, ANONYMOUS
●
●
●
Anon%mous function can be created using the ke%word lambda E*ample& HHH isZeen J lambda n& False if n JJ 0 or n X - else
OB;ECT ORIENTED PROGRAMMING (OOP)
OOP, INTRODUCTION
●
●
$rogramming paradigm paradigm based on the concept of data structure reoling around ob2ects rather than actions Mb2ect contain attributes ,ariable ,ariable within the scope of the ob2ect and methods ,functions within the ob2ect
●
●
n $%thon9 eer%thing is an ob2ect
●
E*ample& HHH a J 1 N HHH t%pe,a
OOP, DE!INING A CLASS
●
●
sing class class ke%word ke%word E*ample& HHH class =%7lass& N def ZZinitZZ,se ZZinitZZ,self9 lf9 sa%J:what:& N self.sa% J sa% N def shout,self& N print,self.sa% N HHH a J =%7lass,:(ello9 worldG: HHH a.shout, HHH a.sa% J :3hat sa% %ou6: HHH a.shout,
OOP, ARBITRARY DATA STRUCTURE
●
●
$%thon allow %ou to create a new data structure E*ample& HHH class $oint& N def ZZinitZZ,se ZZinitZZ,self9 lf9 *9 %& N self.*9 self.% J *9 % N def ZZaddZZ,sel ZZaddZZ,self9 f9 pt& N return $oint,self.* $oint,self.*Ipt.*9 Ipt.*9 self.%Ipt.% N def ZZsubZZ,sel ZZsubZZ,self9 f9 pt& N return $oint,self.* $oint,self.*)pt.*9 )pt.*9 self.%)pt.% N def ZZe+ZZ,self9 pt& N return self.* JJ pt.* and self.% JJ pt.%
OOP, INHERITANCE
●
●
erie a class from a base class E*ample& HHH class <%re& N def ZZinitZZ,se ZZinitZZ,self9 lf9 nJ#& N self.numt%re J num N HHH class 7olor& N def ZZinitZZ,se ZZinitZZ,self9 lf9 cJ:red:& N self.color J c N
●
●
E*ample ,cont& HHH class 7ar,<%re& N def ZZinitZZ,sel ZZinitZZ,self& f& N super,7ar9 self.ZZinitZZ, N HHH a J 7ar, HHH a.numt%re >how multiple inheritance +uirks
ERRORS 1 ECEPTIONS
ERRORS 1 ECEPTIONS
●
●
●
●
>%nta* error
–
E*ceptions
>%nta* error e*ample& HHH if a ok E*ceptions e*amples& HHH S HHH # I C1D E*ception happens when the s%nta* is correct during e*ecution but error is detected
ECEPTION HANDLING
●
●
nlike s%nta* error9 e*ception can be handle b% %our code E*ample& HHH tr%& N S/0 N e*cept ameError& N print,Con:t know what S isGGD N e*cept WeroiisionError& N print,C7an:t diide S with 0GD N e*cept& N print,C>ome other errorD N HHH
ECEPTION HANDLING (CONT)
●
●
●
Another e*ample& HHH tr%& N S/0 N e*cept ,ameError9 WeroiisionError as e& N print,CErr print,CError& or& U0V.format,e.args U0V.format,e.argsQ0R Q0R N e*cept& N print,:some other error: N
RAISING ECEPTION
●
●
●
E*ception can be manuall% raised using the ke%word raise E*ample& HHH raise ameError,:duhG Yar is not defined: Another e*ample using custom error& HHH class =%7ustomError,E*ception& N pass N HHH raise =%7ustomError,:wowG m% own error:
MODULES
MODULE, INTRODUCTION
●
●
●
●
●
A module is a file ,with .p% e*tension containing $%thon definitions and statements.
MODULE, EAMPLE
●
7reate a file called m%mod.p% ,this will be %our module def func1,& print ,:func1 from m%mod: def func-,& print,:func- from m%mod:
●
●
Mpen $%thon shell from the same director% HHH import m%mod HHH m%mod.func1, HHH m%mod.func-, =odule is accessed using dot notation
MODULE, PAC:AGE
●
$ackage is a wa% to structuring or organising modules into a more logical collection as %ou see fit
BATTERIES INCLUDED
BATTERIES INCLUDED
●
●
●
●
●
>tandard installation of $%thon comes with lots of built)in functions and an arra% of standard libraries. libraries. n some cases9 these functions and libraries are all %ou need to build %our application.
BUILT4IN !UNCTIONS
●
enumerate,Qse+9 startJ0R
●
rawZinput,QpromptR
●
len,s
●
range,Qstart9R stopQ9 stepR9 *range,
●
open,nameQ9 modeR
●
set,QiterableR
●
int,9 oct,9 he*,9 bin,
STANDARD LIBRARIES
●
s%s
●
os
●
time
●
datetime
●
math
●
decimal
●
logging
●
doctest unittest
Introductory Course: Practical Python Programming
INTRODUCTORY COURSE TO PRACTICAL PYTHON PROGRAMMING
Engku Ahmad Faisal
[email protected] github.com/efaisal twitter.com/efaisal facebook.com/eafaisal plus.google.com/1000858!!"8!#551
I
EAF i l
1
Introductory Course: Practical Python Programming
ABOUT THIS COURSE ●
Fundamental course on programming and $%thon
●
da%s
●
Format&
●
●
I
EAF i l
–
'ectures
–
(ands)on e*ercises
–
(andout
Feel free to ask +uestion an%time Alwa%s use the official $%thon documentation ,https&//docs.p%thon.org/-/ or https&//docs.p%thon.org//
2
Introductory Course: Practical Python Programming
INTRODUCING PROGRAMMING What is Programming? ●
●
●
I
EAF i l
nstruction to do something to achiee a desired result sing series of steps or actions that a programmer defines ,procedure Each action works on certain ob2ect,s or data in order to attain a well defined goal
3
Introductory Course: Practical Python Programming
REAL WORLD EAMPLE O! PROGRAMMING Sham"oo Instr#$tion ●
3ash
●
4inse
●
4epeat
o %ou notice the problem with the instruction6
I
EAF i l
4
Introductory Course: Practical Python Programming
COMPUTER PROGRAMMING
●
●
●
I
EAF i l
7omputer is a dumb deice that cannot understand human h uman language ou9 as a programmer9 need to tell the computer c omputer precisel% what to do se programming language which helps to translate %our instruction so that computer can understand
5
Introductory Course: Practical Python Programming
WHAT IS PYTHON? An O%&r%i&' ●
●
●
I
EAF i l
A high leel9 general purpose programming language (igh leel& don:t need to know the details of hardware ;eneral purpose& can be used to build man% kind of applications ,s domain specific language such as (<='9 >?'9 =A<'A
6
Introductory Course: Practical Python Programming
WHAT IS PYTHON? ($ont) A *itt*& histor+, ●
esigned b% ;uido an 4ossum
●
First release in 11
●
●
I
EAF i l
(as man% implementation& 7$%thon9 $%$%9 B%thon9 ron$%thon 3e:ll be using the reference implementation& 7$%thon
7
Introductory Course: Practical Python Programming
WHAT IS PYTHON? ($ont) Wh+ *&arn P+thon?
I
EAF i l
●
'ow learning cure
●
CEnforceD good programming practice
●
=ulti)platforms& 3indows9 'inu*9 =ac
●
CatteriesD included
Introductory Course: Practical Python Programming
WHAT IS PYTHON? ($ont) E-am"*&s o. a""*i$ations that $an /& /#i*t #sing P+thon, ●
esktop applications/games
●
3eb)based applications
●
●
I
EAF i l
>%stem administrator tasks automation >cientific engineering data anal%sis
!
Introductory Course: Practical Python Programming
WHAT IS PYTHON? ($ont) Who #s&s P+thon? ●
●
;iant companies goernment agencies& –
;oogle9 ropbo*9 nstagram
–
7E49 A>A
n =ala%sia& –
●
<=9 7EF9 >tar ewspaper
ouG ownload from www.p%thon.org
>how demo& 1. ;ame -. Facial recognition
I
EAF i l
1"
Introductory Course: Practical Python Programming
INTRODUCING IDLE
I
EAF i l
●
'E is an integrated deelopment enironment
●
$art of $%thon standard librar% using
●
$roides $%thon shell and a te*t editor
●
ot great but good enough for our purpose
11
Introductory Course: Practical Python Programming
0ALUE 1 EPRESSION
●
●
●
●
●
I
EAF i l
<%pe on the $%thon shell& HHH 1 I As e*pected the result is
12
Introductory Course: Practical Python Programming
STORING 0ALUE
●
>tore into ariable
●
sing the J sign
●
I
EAF i l
E*amples& HHH ar J HHH ar HHH a J 1 HHH ar I a HHH result J ar I a HHH result
13
Introductory Course: Practical Python Programming
DATATYPES, NUMBERS
●
ntegers
●
HHH a J HHH t%pe,a Kclass :int:H HHH ●
I
EAF i l
HHH import fractions HHH L >imulate 1/ HHH c J fractions.Fraction,19 HHH c Fraction,19 HHH
Floats HHH b J -.5 HHH t%pe,b Kclass :float:H HHH
Fractions
●
7omple* numbers
14
Introductory Course: Practical Python Programming
DATATYPES, NUMBERS ($ont) 7ommon Mperators for umbers
2
Addition
4
>ubstraction
35
6
=ultiplication
7
8
iision
9
I
EAF i l
3
75
;reater than ;reater than or e+ual to 'esser than 'esser than or e+ual to
=odulus ,calculate remainder
15
Introductory Course: Practical Python Programming
PRIMITI0E DATATYPES
I
EAF i l
16
Introductory Course: Practical Python Programming
DATATYPES, STRINGS
●
Enclosed b% single +uotes HHH :this is a string: :this is a string: HHH
●
Enclosed b% double +uotes HHH Cthis is also a stringD :this is also a string: HHH
I
EAF i l
●
Enclosed b% triple single or double +uotes for multilines string HHH :::first multi N line string::: :first multiOnline string: HHH CDDsecond multi N line stringDDD :second multiOnline string: HHH
17
Introductory Course: Practical Python Programming
DATATYPES, STRINGS
●
●
I
EAF i l
7oncatenate HHH a J :m% : HHH a I :string: :m% string: HHH
●
'ong string HHH m%str J ,:put in bracket : N :to handle long string: HHH m%str :put in bracket to handle N :
4epeat HHH b J :ha : HHH b P :ha ha ha : HHH
1
Introductory Course: Practical Python Programming
DATATYPES, STRING
●
I
EAF i l
>tring is a se+uence of characters can be inde*ed/subscripted HHH m%str J :$%thon: HHH m%strQ0R :$: HHH m%strQ5R :n: HHH m%strQ)1R :n: HHH m%strQ)!R :$:
1!
Introductory Course: Practical Python Programming
DATATYPE, STRINGS
●
●
I
EAF i l
>tring is a se+uence of characters can be sliced HHH m%str J :$%thon: HHH m%strQ1&R :%thon: HHH m%strQ1&5R :%tho: HHH
2"
Introductory Course: Practical Python Programming
BASIC DATA STRUCTURE
I
EAF i l
21
Introductory Course: Practical Python Programming
DATA STRUCTURE, LIST
●
●
●
●
●
I
EAF i l
=utable ,changeable9 compound ,group of alues data t%pe lank lists HHH a J QR HHH b J list, 'ists with default alues HHH a J Q19 -9 9 #R HHH b J Q:*:9 :%:9 :S:R 'ook at the aailable methods to manipulate list 'ist comprehension& a more adance topic on list will be coered later
22
Introductory Course: Practical Python Programming
DATA STRUCTURE, TUPLE
●
●
●
●
I
EAF i l
mmutable ,unchangeable9 compound ,group of alues data t%pe lank tuples HHH a J , HHH b J tuple,
23
Introductory Course: Practical Python Programming
DATA STRUCTURE, DICTIONARY
●
●
●
I
EAF i l
=apping datat%pe ,ke%)alueT similar to associatie arra% in some languages lank dictionaries HHH a J UV HHH b J dict, ictionaries with alues HHH a J U:a:& 19 :b:& -V HHH b J dict,,,:a:9 19 ,:b:9 -
24
Introductory Course: Practical Python Programming
CONTROL !LOWS
I
EAF i l
25
Introductory Course: Practical Python Programming
CONTROL !LOW, I!
●
●
I
EAF i l
7onditional control flow E*ample ,ote& identation is # spaces& HHH * J 5 HHH if * K 0& N print,:egatie alue: N elif * JJ 0& N print,:Wero: N elif * H 0 and * K 11& N print,:etween 1 and 10: N else& N print,:=ore than 10: :etween 1 and 10: HHH
26
Introductory Course: Practical Python Programming
CONTROL !LOW, !OR
●
●
I
EAF i l
terates oer items in iterables ,e.g. list9 tuple E*ample& HHH for n in range,-9 10& N for * in range,-9 n& N if n X * JJ 0& N break N else& N print,n9 :is a prime number: L $%thon N print n9 :is a prime number: L $%thon -
●
break is is used to terminate iteration
●
else is else is e*ecuted if no break occurs occurs in the for iteration iteration
27
Introductory Course: Practical Python Programming
CONTROL !LOW, !OR
●
●
I
EAF i l
Another e*ample& HHH for i in range,-9 10& N if i X - JJ 0& N print,i9 : is an een number: L $%thon N print i9 : is an een number: L $%thon N continue N print,i9 : is an odd number: L $%thon N print i9 : is an odd number: L $%thon continue ke%word continue ke%word means continues with ne*t iteration
2
Introductory Course: Practical Python Programming
CONTROL !LOW, WHILE
●
●
●
I
EAF i l
sed to loop or repeat a section of code for as long as the condition ,e*pression defined in the statement is true E*ample9 to loop foreer& HHH while
2!
Introductory Course: Practical Python Programming
!UNCTIONS
I
EAF i l
3"
Introductory Course: Practical Python Programming
WHAT IS A !UNCTION?
●
●
●
I
EAF i l
A named section of a program that performs specific task Allow to organiSe code block which repeatedl% used into a reusable procedure or routine $%thon comes with a lot of built)in functions which we alread% seen some of them
31
Introductory Course: Practical Python Programming
!UNCTION, DE!INING
●
●
●
●
●
I
EAF i l
sing the ke%word def Followed b% a name9 patentheses ,for possible arguments and a colon od% of a function must be indented Yariables defined in a function is stored in the local s%mbol table
●
E*ample& Fibonacci series HHH def fib,n& N CDDoc stringDDD N a9 b J 09 1 N while a K n& N print a9 L $%N print,a9 endJ: : L $% N a9 b J b9 aIb N print, L $% N HHH fib,-000
=a% return a alue using return ke%word return ke%word
32
Introductory Course: Practical Python Programming
!UNCTION, DE!AULT ARGUMENT
●
●
●
●
I
EAF i l
>ometimes it:s useful to define default alue to argument of a function E*ample& HHH def calculate,arg9 alJ1& N efault alue is ealuated at the point of function d efinition and ealuated on once E*ample& HHH i J HHH def f,argJi& N HHH i J 5
33
Introductory Course: Practical Python Programming
!UNCTION, :EYWORD ARGUMENT
●
●
I
EAF i l
Function can be called using ke%word argument E*ample& HHH def func,arg1J19 sa%J:hello:9 argJ5& N print,sa% N print,arg1 N print,arg HHH func,sa%J:world: L sing ke%word argument HHH func,19 :world: L sing positional arguments HHH func, L sing default arguments HHH
34
Introductory Course: Practical Python Programming
!UNCTION, ARBITRARY ARGUMENT
●
●
I
EAF i l
35
Introductory Course: Practical Python Programming
!UNCTION, ANONYMOUS
●
●
●
I
EAF i l
Anon%mous function can be created using the ke%word lambda E*ample& HHH isZeen J lambda n& False if n JJ 0 or n X - else
36
Introductory Course: Practical Python Programming
OB;ECT ORIENTED PROGRAMMING (OOP)
I
EAF i l
37
Introductory Course: Practical Python Programming
OOP, INTRODUCTION
●
●
EAF i l
Mb2ect contain attributes ,ariable within the scope of the ob2ect and methods ,functions within the ob2ect
●
●
n $%thon9 eer%thing is an ob2ect
●
I
$rogramming paradigm based on the concept of data structure s tructure reoling around ob2ects rather than actions
E*ample& HHH a J 1 N HHH t%pe,a
3
Introductory Course: Practical Python Programming
OOP, DE!INING A CLASS
●
●
I
EAF i l
sing class class ke%word ke%word E*ample& HHH class =%7lass& N def ZZinitZZ,self9 sa%J:what:& N self.sa% J sa% N def shout,self& N print,self.sa% N HHH a J =%7lass,:(ello9 worldG: HHH a.shout, HHH a.sa% J :3hat sa% %ou6: HHH a.shout,
3!
Introductory Course: Practical Python Programming
OOP, ARBITRARY DATA STRUCTURE
●
●
I
EAF i l
$%thon allow %ou to create a new data structure E*ample& HHH class $oint& N def ZZinitZZ,self9 *9 %& N self.*9 self.% J *9 % N def ZZaddZZ,self9 pt& N return $oint,self.*Ipt.*9 self.%Ipt.% N def ZZsubZZ,self9 pt& N return $oint,self.*)pt.*9 self.%)pt.% N def ZZe+ZZ,self9 pt& N return self.* JJ pt.* and self.% JJ pt.%
4"
Introductory Course: Practical Python Programming
OOP, INHERITANCE
●
●
I
EAF i l
erie a class from a base class E*ample& HHH class <%re& N def ZZinitZZ,self9 nJ#& N self.numt%re J num N HHH class 7olor& N def ZZinitZZ,self9 cJ:red:& N self.color J c N
●
●
E*ample ,cont& HHH class 7ar,<%re& N def ZZinitZZ,self& N super,7ar9 self.ZZinitZZ, N HHH a J 7ar, HHH a.numt%re >how multiple inheritance +uirks
41
Introductory Course: Practical Python Programming
ERRORS 1 ECEPTIONS
I
EAF i l
42
Introductory Course: Practical Python Programming
ERRORS 1 ECEPTIONS
●
●
●
●
I
EAF i l
>%nta* error
–
E*ceptions
>%nta* error e*ample& HHH if a ok E*ceptions e*amples& HHH S HHH # I C1D E*ception happens when the s%nta* is correct co rrect during e*ecution but error is detected
43
Introductory Course: Practical Python Programming
ECEPTION HANDLING
●
●
I
EAF i l
nlike s%nta* error9 e*ception can be handle b% %our code E*ample& HHH tr%& N S/0 N e*cept ameError& N print,Con:t know what S isGGD N e*cept WeroiisionError WeroiisionError&& N print,C7an:t diide S with 0GD N e*cept& N print,C>ome other errorD N HHH
44
Introductory Course: Practical Python Programming
ECEPTION HANDLING (CONT)
●
●
●
I
EAF i l
Another e*ample& HHH tr%& N S/0 N e*cept ,ameError9 WeroiisionError as e& N print,CError& U0V.format,e.argsQ0R U0V.format,e.argsQ0R N e*cept& N print,:some other error: N
45
Introductory Course: Practical Python Programming
RAISING ECEPTION
●
●
●
I
EAF i l
E*ception can be manuall% raised using the ke%word raise E*ample& HHH raise ameError,:duhG Yar is not defined: Another e*ample using custom error& HHH class =%7ustomError,E*ceptio =%7ustomError,E*ception& n& N pass N HHH raise =%7ustomError,:wowG m% own error:
46
Introductory Course: Practical Python Programming
MODULES
I
EAF i l
47
Introductory Course: Practical Python Programming
MODULE, INTRODUCTION
●
●
●
●
●
I
EAF i l
A module is a file ,with .p% e*tension containing $%thon definitions and statements.
4
Introductory Course: Practical Python Programming
MODULE, EAMPLE
●
7reate a file called m%mod.p% ,this will be %our module def func1,& print ,:func1 from m%mod: def func-,& print,:func- from m%mod:
●
●
I
EAF i l
Mpen $%thon shell from the same director% HHH import m%mod HHH m%mod.func1, HHH m%mod.func-, =odule is accessed using dot notation
4!
Introductory Course: Practical Python Programming
MODULE, PAC:AGE
●
I
EAF i l
$ackage is a wa% to structuring or organising modules into a more logical collection as %ou see fit
5"
Introductory Course: Practical Python Programming
BATTERIES INCLUDED
I
EAF i l
51
Introductory Course: Practical Python Programming
BATTERIES INCLUDED
●
●
●
●
●
I
EAF i l
>tandard installation of $%thon comes with lots of built)in functions and an arra% of standard libraries. n some cases9 these functions and libraries are all %ou need to build %our application.
52
Introductory Course: Practical Python Programming
BUILT4IN !UNCTIONS
I
EAF i l
●
enumerate,Qse+9 startJ0R
●
rawZinput,QpromptR
●
len,s
●
range,Qstart9R stopQ9 stepR9 *range,
●
open,nameQ9 modeR
●
set,QiterableR
●
int,9 oct,9 he*,9 bin,
53
Introductory Course: Practical Python Programming
STANDARD LIBRARIES
I
EAF i l
●
s%s
●
os
●
time
●
datetime
●
math
●
decimal
●
logging
●
doctest unittest
54