Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
73 views

Python Tutorial2 PDF

This document provides an introduction to Python syntax and concepts. It begins with goals of learning Python and reading/writing Python code. It then covers some key Python "isms" like dir, help and indentation. The remainder of the document discusses Python fundamentals like data types, variables, strings, lists, dictionaries, functions, conditionals and iteration. Key points covered include Python's interactive REPL, object model, built-in data structures, string formatting, documentation via docstrings and help, and flow control.

Uploaded by

Murali Dharan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
73 views

Python Tutorial2 PDF

This document provides an introduction to Python syntax and concepts. It begins with goals of learning Python and reading/writing Python code. It then covers some key Python "isms" like dir, help and indentation. The remainder of the document discusses Python fundamentals like data types, variables, strings, lists, dictionaries, functions, conditionals and iteration. Key points covered include Python's interactive REPL, object model, built-in data structures, string formatting, documentation via docstrings and help, and flow control.

Uploaded by

Murali Dharan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 99

Goal

● ReadPython
● WritePython
Discl aimer
● Assumesomeprogrammingexperience
● Notcoveringallapi's,justsyntax
ThreePython'ismstoRemember
● dir
● help
● colon/indentshufle
WhyPython?
Python is a powerful, multi-paradigm,
interpreted language popular with
start-upsandlargeCo’s
Python 2or3?
For beginers there is no real
difference between Python2&3. The
basics are the same(except for
print)
Hello World
Hello worl d
print " h e l l o world"
F rom int erpret er
$ python
>>> pri nt " hel l o wor l d"
h e l l o world
REPL
Read,Eval,Print,Loop
REPL
$ python
>>> 2 + 2 # read, eval
4 # print
>>> # r epeat ( l oop)
REPL (2)
Many developers keep a REPL
handy during programming
From script
Makefilehello.py with
p r i n t " h e l l o world"

Runwith:pyt hon hel l o. py


(unix)script
Makefilehello with
#! / us r / bi n/ env pyt hon
p r i n t " h e l l o world"

Runwith:
chmod +x h e l l o
./hello
Python3 helloworld
p r i n t is no longer a
statement,but a function
p r i n t ( " h e l l o world")
Objects
Object s
Everything in Python is an object that has:
● An identity(id)
● A value(mutableorimmutable)
id
>>> a = 4
>>> i d( a )
6406896
Val ue
● Mutable:When you alter the item, the
i d is still the same .Dictionary, List
● Immutable:String, Integer, Tuple
Mut abl e
>>> b = [ ]
>>> i d ( b )
140675605442000
>>> b.ap p en d( 3 )
>>> b
[3]
>>> i d ( b )
140675605442000 # SAME!
Immut abl e
>>> a = 4
>>> i d( a )
6406896
>>> a = a + 1
>>> i d ( a )
6406872 # DIFFERENT!
Variabl es
a = 4 # Integer
b = 5.6 # Float
c = "hello" # String
a = "4" # rebound t o S t r i n g
Naming
● lowercase
● underscore_between_words
● don't start with numbers
PEP
Python Enhancement Proposal(similar to
JSR in Java)

PEP stands for Python Enhancement Proposal. A PEP is a

design document providing information to the Python

community, or describing a new feature for Python or its

processes or environment. The PEP should provide a concise

technical specification of the feature and a rationale for the

feature
Math
Mat h
+ , - , * , / , * * (power),%(modulo)
Careful with integer division

>>> 3/ 4 0
>>> 3/ 4.
0.75

(In Python3// is integer division


operator)
What happens when you
raise10 to the
100th?
Lo ng
>>> 10**100
10000000000000000000000000000000
00000000000000000000000000000000
00000000000000000000000000000000
00000L
Lo ng (2)
>>> import sys
>>> s y s . m a x i n t
9223372036854775807
>>> s y s . m a x i n t + 1
9223372036854775808L
Strings
Strings
name = ' m a t t '
wi t h_quot e = " I a i n' t gonna "
l o n g e r = " " " T h i s s t r i n g has
multiple l i n e s
in it"""
How do I print?
He said,“I’msorry”
St ring escaping
Escape with \
>>>pri nt ' He s a i d, " I \ ' m s or r y" '
He s a i d , " I ' m s o r r y "

>>> print' ' ' H e s a i d , "I'm s o r r y " ' ' '


He s a i d , " I ' m s o r r y "
>>> print """He s a i d , " I ' m s o r r y \ " " " "
He s a i d , " I ' m s o r r y "
String escaping(2)
Escape Sequence Output
\\ Backslash
\' Single quote
\" Double quote
\b ASCII Backspace
\n Newline
\t Tab
\u12af Unicode 16 bit
\U12af89bc Unicode 32 bit
\o84 Octal character
\xFF Hex character
String formatting
c-like
>>> " %s %s " %( ' hel l o' , ' wor l d' )
' h e l l o wo r l d '

PEP3101style
>>> " { 0} { 1} " . f or ma t ( ' hel l o' , ' wor l d' )
' h e l l o wo r l d '
Methods & dir
di r
Lists attributes and methods:
>>> d i r ( " a s t r i n g " )
[ ' add ' , ' c l a s s ' , . . . ' s t a r t s w i t h ' , ' s t r i p ' ,
'swapcase', ' t i t l e ' , ' t r a n s l a t e ' , 'upper', ' z f i l l ' ]
Whats with all the
‘ blah ' ?
dunder met hods
dunder (double under) or "special/magic"
methods
hel p
>>> h e l p ( " a s t r i n g " . s t a r t s w i t h )

Help on b u i l t - i n f u n c t i o n s t a r t s w i t h :

startswith(...)
S . s t a r t s w i t h ( p r e f i x [ , s t a r t [ , e n d ] ] ) -> bool

Ret ur n Tr ue i f S s t a r t s wi t h t he s peci f i ed pr ef i x, Fa l s e
otherwise.
With o p t i o n a l s t a r t , t e s t S b e g i n n i n g a t t h a t p o s i t i o n .
Wi t h opt i ona l end, s t op compa r i ng S a t t ha t pos i t i on.
p r e f i x can a l s o be a t u p l e o f s t r i n g s to t r y .
Stringmethods
● s.endswith(sub)
Returns True if endswith sub
● s .find(sub)
Returns indexof sub or-1
● s.format(*args)
Places args in string
Stringmethods(2)
● s.index(sub)
Returns index of sub or exception
● s.join(list)
Returns list items separated by
string
● s.strip()
Removes white space from start/end
Comments
comments
Comments follow by #
comments
No multi-line comments
MoreTypes
None
Pythonic way of saying NULL.
Evaluates toFalse.
c = None
booleans
a = True
b = Fa l s e
sequences
● lists
● tuples
● sets
l ist s
Hold sequences.
How would we find out the
attributes& methods of a list?
l ist s
>>> d i r ( [ ] )
[ ' add ' , ' c l a s s ' , ' c o n t a i n s ' , . . .
' i t e r ' , . . . ' len ' , . . . , 'append', 'count',
' ext end' , ' i ndex' , ' i ns er t ' , ' pop' , ' r emove' ,
'reverse', 's o r t ']
l ist s
>>> a = []
>>> a . ap p e n d ( 4 )
>>> a.append('hello')
>>> a . ap p e n d ( 1 )
>>> a . s or t ( ) # i n pl ac e
>>> print a
[ 1, 4, ' hel l o' ]
l ist s
How would we find out documentation
for a method?
l ist s
h e l p function:
>>> h e l p ( [ ] . a p p e n d )
Help on b u i l t - i n f u n c t i o n append:

append(...)
L. append( obj ect ) - - append obj ect t o end
Listmethods
● l.append(x)
Insert x at end of list
● l.extend(l2)
A d d l 2 items to list
● l.sort()
In place sort
Listmethods(2)
● l.reverse()
Reverse list in place
● l.remove(item)
Remove first item found
● l.pop()
Remove/return item at end of list
Dictionaries
dict io naries
Also called hashmap or
associativearray
>>>age = { }
>>> a g e [ ' g e o r g e ' ] = 10
>>> a g e [ ' f r e d ' ] = 12
>>> a g e [ ' h e n r y ' ] = 10
>>> pri nt a g e[ ' g eor g e' ]
10
dictionaries (2)
Find out if 'matt' in age
>>> ‘ m a t t ’ i n age
False
.g et
>>> print a g e [ ' c h a r l e s ' ]
Traceback (most recent c a l l l a s t ) :
Fi l e " <s t di n>" , l i ne 1, i n <modul e>
KeyError : ' c h a r l e s '
>>> pri nt a g e. g et ( ' cha r l es ' , ' Not f ound' )
Not found
del et ing keys
Removing 'charles' from age
>>> del a g e [ ' c h a r l e s ' ]
Functions
f unct ions
def add_2(num):
""" return2
mor e t han
num " " "
ret urn num + 2

f i v e = add_2(3)
f unct ions (2)
● def
● function name
● (parameters)
● : +indent
● optional documentation
● body
● return
Whit e space
Instead of use : and indent
consistently(4spaces)
default(named)parameters
def a dd_n( num, n=3) :
" " " d e fa u l t t o adding
3 " " " return num +
n

f i v e = add_n(2)
ten = add_n(15, - 5 )
doc
Functions have docstrings. Accesible
via . doc or help
doc
>>> def e c h o ( t x t ) :
... " echo ba ck t xt "
... return t x t
>>> h e l p ( e c h o )
Hel p on f unct i on echo i n modul e ma i n :
<BLANKLINE>
echo(txt)
echo back t x t
<BLANKLINE>
naming
● lowercase
● underscore_between_words
● don't start with numbers
● verb
SeePEP8
Conditionals
condit ional s
i f g r a de > 90:
print "A"
el i f g r a de > 80:
print " B "
el i f g r a de > 70:
print "C"
el s e:
print "D"
Rememberthe
colon/whitespace!
B o o leans
a = True
b = Fa l s e
Comparison Operat ors
Suports(>,>=,<,<=,==,!=)
>>> 5 > 9
False
>>> ' ma t t ' ! = ' f r ed'
True
>>>i s i ns t a nce( ' ma t t ' , b a s e s t r i n g )
True
B o o lean Operators
and,or,not (for logical),
&,|,and ^ ( f o r bitwise)
>>> x = 5
>>> x < - 4 or x > 4
True
B o o l ean note
Parens are only required for precedence
i f (x > 10):
print " B i g "

Same as
i f x > 10:
print " B i g "
Chained comparisons
i f 3 < x < 5:
print " F o u r ! "

Same as
i f x > 3 and x < 5:
print " F o u r ! "
Iteration
it erat ion
for number i n [ 1 , 2 , 3 , 4 , 5 , 6 ] :
print number

for number i n r a n g e ( 1 , 7 ) :
print number
range n o t e
Python tends to follow
half-openinterval ( [ s t a r t , e n d ) ) w i t h
r a n g e and slices.
● end-start=length
● Easy to concat ranges w/ooverlap
iteration(2)
Java/C-es que style of object in array
acess(BAD):
animals = [ " c a t " , "dog", " b i rd " ]
for index i n r a n g e ( l e n ( a n i m a l s ) ) :
print i n d e x , a n i m a l s [ i n d e x ]
iteration(3)
If you need indices,use enumerate
animals = [ " c a t " , "dog", " b i rd " ]
for i n d e x , v a l u e i n e nu m e r at e ( a n i m a l s ) :
print i n d e x , v a l u e
iteration(4)
Can break out of nearest loop
for item i n sequence:
# process u n t i l f i r s t negati ve
i f item < 0 :
break
# process item
iteration(5)
Can continue to skipover items
for item i n sequence:
i f i t em < 0:
cont i nue
# pr oc es s al l pos i t i v e i t ems
iteration(6)
Can loop over lists,strings,iterators,
dictionaries...sequence like things:
my_dict = { "name": " m a t t " , " c a s h " : 5 . 4 5 }
for key i n my _ d i c t . ke y s ( ) :
# p r o c e s s ke y

for v a l u e i n m y _ d i c t . v a l u e s ( ) :
# process value

for ke y, v a l u e i n my _ d i c t . i t e m s ( ) :
# process items
pas s
p a s s is a null operation
for i i n r a n g e ( 1 0 ) :
# do not hi ng 10 t i mes
pass
Slicing
Sl icing
Sequences(lists,tuples,strings,etc)can
be sliced to pull out a single item
my_pet s = [ " dog " , " ca t " , " bi r d" ]
f a v o r i t e = my_pets[0]
b i r d = my_pets[-1]
Slicing(2)
Slices can take an end index,to pull
out a list of items
my_pets = [ " d o g " , " c a t " , " b i r d " ]
# a list
cat_and_dog = my_pets[0:2]
cat_and_dog2 = my_pets[: 2]
ca t _a nd_bi r d = my_pet s [ 1: 3]
ca t _a nd_bi r d2 = my_pet s [ 1: ]
File IO
FileInput
Open a file to read from it(oldstyle):
f i n = open("foo.txt")
for l i n e i n f i n :
# mani pul at e l i ne

fin.close()
FileOutput
Open a file using 'w' to write to a
file:
f out = open( " ba r. t xt " , " w" )
f o u t . w r i t e ( " h e l l o world" )
fout.close()
Always remember to
closeyourfiles!
closingwithwith
implicitclose (new2.5+style)
wi t h open( ' ba r . t xt ' ) as f i n:
f or l i ne i n f i n:
# pr oc es s l i ne
Classes
Cl asses
c l a s s Animal(object):
def i ni t ( s el f , na me) :
s e l f . n a m e = name

def t a l k ( s e l f ) :
print "Generic Animal Sound"

a ni ma l = Ani ma l ( " t hi ng " )


animal.talk()
Cl as es(2)
Subclassing
c l a s s Cat(Animal):
def t a l k( s el f ) :
pri nt ' %s s ays , " Meow! " ' % ( s el f . na me)

c a t = Cat("Groucho")
ca t . t a l k( ) # i nv oke met hod
Cl as es(3)
c l a s s Cheetah(Cat):
" " " c l as s es c an hav e
docstrings"""

def t a l k ( s e l f ) :
print "Growl"
naming
● Camel Case
● don't start with numbers
● Nouns

You might also like