Perl and Python

gorgeousvassalΛογισμικό & κατασκευή λογ/κού

7 Νοε 2013 (πριν από 3 χρόνια και 10 μήνες)

85 εμφανίσεις

Perl and Python

ESA 2011/2012

Adam Belloum

a.s.z.belloum@uva.nl



Material

Prepared
by
Eelco

Schatborn


ESA: Python

Today:


1. Python introduction


2. Basic Python: types, variables, statements, . . .


3. Object Orientation


4. Documentation

Regular Expressions


Written by Guido van
Rossum


Started work in 1990


First release in 1991


Minor number release every 6 months


Named after Monty Python



“Perl is executable line noise. Python is
executable pseudo
-
code.”

What is Python


a general
-
purpose high
-
level programming language
whose design philosophy emphasizes
code readability
.



Python aims to combine "remarkable power with very
clear syntax”, and its
standard library

is large and
comprehensive.



Its use of
indentation

for block
delimiters

is
unusual
among popular programming languages.



Python supports multiple programming paradigms,
primarily but not limited to object oriented

http://en.wikipedia.org/wiki/Python_%28programming_language%29

Perl vs. Python


Perl is worse than Python because people
wanted it worse.

Larry Wall, 14 Oct 1998




I would actively encourage my
competition to use Perl.
Sean True, 30 Mar 1999



Why I Love Python ©2001
www.BruceEckel.com

10 Reasons to Learn the Python
Programming Language

1.
Reduced Clutter

2.
It’s not backward
-
compatible in exchange for pain

3.
It doesn’t value performance over my productivity

4.
It doesn’t treat me like I’m stupid

5.
I don’t wait forever for a full implementation of the
language

6.
It doesn’t make assumptions about how we discover
errors

7.
Marketing people are not involved

8.
I don’t have to type so much

9.
My guesses are usually right

10.
Python lets me focus on
concepts

Why I Love Python ©2001
www.BruceEckel.com

Weak typing


“You write
what

you want to do, let Python worry about
ho”



weakly typed programming languages are those that
support either implicit type conversion



advantage claimed of weak typing is that it requires less
effort on the part of the programmer, because the
compiler

/
interpreter

implicitly performs certain
conversions


Argument against weak typing: “errors won’t be found”



Simple Python

A simple program to start with:




#!/
usr
/bin/python

principal = 1000

# initial amount

rate = 0.05




# interest rate

numyears

= 5

# number of years

year = 1

while year <=
numyears
:




principal = principal*(1+rate)




print year, principal




year += 1

The Python Interpreter


Normal method for scripting using

#!/
usr
/bin/python




python is also an interactive interpreter

you can interpret single lines of code

good for simple checking and debugging




Extensible in Python, C and other programming
languages


Object Oriented without being Object
-
centric


White
-
space is significant


Good for scripting.

Numbers (1)

simple numbers the same as with
perl
:


decimal:
12,
-
17, 255, …


octal, start with
0
: 015,
-
023, 0777, …


hexadecimal, start with
0x
: 0xc,
-
0x11, 0xff,…


floating point numbers:


”one and a quarter":
1.25


But also imaginary numbers:


written as `
imagj
', for example:
1.23j

Numbers (2)


Complex numbers, using imaginary numbers:


written as
(real +
imagj
), or can be created with the
complex(real
,
imag
)

function.



1.0j *1J ! (
-
1+0j)

Strings (1)


To create string literals, enclose them in
single
,
double
or
triple quotes
.


Examples:

'
Hello World
'

"
Python is groovy
"

"""
Sino
si

Pepito

Biglangliko
?
"""



The same type of quote used to start the string must
be used to terminate it.

String (2)


Escape sequences represent special characters:

\
n
,
\
t
, . . .


Both

in
double quoted
(
"
) and single quoted (
'
)
strings


For
verbatim
strings use raw strings using
r
'
. . .
'

>>> print "Hi there!
\
n

\
t

It's me.
\
n
"

Hi there!

It's me.

>>> print
r'
And

me
\
n

\
t

as well!
'

And me
\
n

\
t

as well!

Strings (3)


Triple
-
quoted
strings using either
“””

or
‘’’

capture all
the text
that appears before the terminating triple quote.



Single
and
double
quoted strings
must be on one logical
line.



Triple
-
quoted
strings are useful when contents of the
string span
multiple lines
of text. For example:

print
"””

Usage: thingy [OPTIONS]


-
h






Display this usage message


-
H hostname

Hostname to connect to

"””

Strings (4)


String literals can
span multiple lines
using a closing
backslash ('
\
')


The backslash is for syntax purposes only, it is not
included in the output


>>> print "Hi
\

there!
\
n
\


\
t

It's me.
\
n



prints:

Hi there!



It's me.

Variables


Python is a
dynamically
typed language: names can
represent values of different types during the
execution of the program.



Names or identifiers


must begin
with a
non
-
numeric character
or
underscore


but may
contain both numeric and non
-
numeric characters

Variables and Numbers


The following operators for numbers apply:






+,
-
, *, /, //, %


Examples





>>> width = 20







>>> height = 5*9






>>> width * height






900

Variables and Strings (1)


Strings can be
concatenated
using a
'
+
'


But also by writing them
adjacent
to each other:


Examples


>>> print "Hello"
+

'Python'


HelloPython


>>> print "Python " "says" ' Hello!'


Python says Hello!


Variables and Strings (2)


Strings are
indexed like lists
, starting at
0


You can use them using the index operator '
[
i
]
'

a = "Hello World"

b

= a[4]




#
b

=
o



Substrings can be used by slicing: `
[
i
:
j
]


c

= a[0:6]



#
c

= "Hello “

d

= a[7:]



#
d

= ”World”

e

= a[3:8]



#
e

= "lo
Wo
"

Variables and Strings (3)


Other data types can be
converted into a string
using
either
str
() or
repr
() functions or
backquotes

(
`
),
which are a shortcut notation for
repr
().


Examples

s

= "The value of
x

is " +
str
(x
)

s

= "The value of
y

is " +
repr
(y
)

s

= "The value of
y

is " +
`
y
`


Play around 1


Write a short python
prog
, which when you enter
our name it prints : Hi ! <your name> .



Hint: use
raw_input
() to get the input


name =
raw_input('What

is your name?
\
n
')

print 'Hi, ' + name + '.'

Lists (1)


lists and
tuples

are sequences of arbitrary objects
You can create a list as follows:

names =
[

"Eric"
,

"
Trixie
"
,

"Coley"
]


They too are indexed:

a = names[2]


# a is now "Coley"

names[0] = ”Jan"

# names is changed


append a new member to the end of a list using
append
()

names
.append
("Khamir
")

Lists (2)


You can
extract
or
reassign
a
portion
of a list by using the
slicing operator.


Examples


names = ["
pusakat","Trixie","Coley","Khamir
"]



b

= names[0
:
2] #
-
> ["
pusakat
", "
Trixie
”]



c

= names[2:] #
-
> ["Coley", "
Khamir
" ]

names[1] = Eric

names[0:2] = [
pusakat
, Eric ]





Use the plus ('
+
') operator to concatenate lists.

a = [1,2,3]
+

[4,5] # Result [1,2,3,4,5]

Lists (3)


Lists can
contain

any kind
of
Python object
including
other lists
.


Example:

a =
[
1,"Dave”,3,
[
"Mark”,9,
[
100, 101
]
]
,10
]



Nested
lists are accessed as follows:

a[1]






# returns "Dave"

a[3][1]







# returns 9

a[3][2][1]




# Returns 101


Play around 2


Write a short python
prog
, which iterate through a
list and print the iteration



Hint: use
enumerate
() to iterate through the list



my_list

= ['john', 'pat', '
gary
', '
michael
']

for
i
, name in
enumerate(my_list
): print
"iteration %
i

is %
s
" % (
i
, name)

Tuples


Tuples

are a lot
like lists


Tuples

support most of the same functions as a list


They are however
immutable
after creation


Used to
return multiple
values from a function


You can create
tuples

by enclosing a group of values
in parentheses
(
'
(
. . .
)
') or with a
comma
-
separated
list.

a =
(
1
,
4
,
5
,
-
9
,
10
)

b

=
(
7
,)
# this is a singleton

person =
(
first_name
,

last_name
,

phone
)

person =
first_name
,

last_name
,

phone

Dictionaries (1)


A
dictionary
is an
associative array

or
hash

table

that contains objects indexed by keys.


Only
immutable
objects can be used as a
key
, like
strings, numbers,
tuples
, etcetera.


You create a dictionary by enclosing values in curly
braces ('
{
. . .
}
'):


a =
{




"
username
"
:

"
xenos
",




"
home
"
:

"/home/
xenos
",




"
uid
"
:
500


}


Dictionaries (2)


Access any value using it's key:


u

=
a["
username
"] # Returns "
xenos
"


d

=
a["
home
"] # Returns "/home/
xenos





To insert or modify objects, you
assign
a
value
to a
key
-
indexed
name.


a["
username
"] = "
trixie
"


a["
home
"] = "/home/
trixie
"


a["
shell
"] = "/
usr/bin/tcsh



Dictionaries (3)

Dictionary membership is
tested
with the
has_key
()
method:

if
a
.has_key
("
username
"):


username =
a["
username
"]

else
:


username = "unknown user"


This can also be performed more compactly this way.

username =
a
.get
("username
", "unknown user")


Dictionaries (4)


To obtain a list of dictionary keys, use the
keys()

method.


k

=
a
.keys
()


#
k

= ["username", "home", "
uid
",
"shell" ]



Use the
del

statement to remove an
element
of a
dictionary.


del

a["
username
"]

Play Around 3



Write a short
prog

in python, which prints amount of money
you have to pay for a given purchase let say: 1 kg (apples

1.40 euro/kg), 3 kg (banana

1.20 euro/kg)



Hit: use dictionary,




prices =
{
'apple'
:

0.40, 'banana'
:

0.50
}

my_purchase

=
{

'apple'
:

1, 'banana'
:

6
}


grocery_bill

= sum(
prices[fruit
] *
\








my_purchase[fruit
]
\










for fruit in
my_purchase
)
\


print 'I owe the grocer $%.2f' %
grocery_bill


Flow control


A block of code contains a list of statements.


Code blocks are denoted by using indentation


Flow control can be
excerted

using looping or
conditional Statements.

Looping Statements (1)


Iterates over the
members of a sequence
, such as a
string
,
list
or
tuple
.


for
i

in (
1
,

2
,

3
,

4
,

5
,

6
,

7
,

8
,

9
):




print "2 to the
%
d

power is
%
d
" %




(
i
, 2**
i
)


Using the
range
() function you can also give a range:


for
i

in
range(
1
,
10
):




print "2 to the %
d

power is %
d
" %




(
i
, 2**
i
)


Looping Statements (2)


The for statement can iterate over any
sequence type
and isn't limited to sequences of integers.


a = "Hello World"


# Print out the characters in a


for

c

in
a:




print
c




b

= ["Eric", "
Trixie
", "Coley", "
Khamir
”]


# Print out the members of a list


for name in
b
:




print name

Looping Statements (3)

# a = [0,1,2,3,4]

#
b

= [1,2,3,4,5,6,7]

#
c

= [0,3,6,9,12]

#
d

= [8,7,6,5,4,3,2]


The
range
(i
,
j
)

function
constructs
a list of integers
with values from
i

to
j



1.


If the starting value is omitted, it's assumed to be
zero.


An optional stride or step size can be given as a third


argument.

a = range(5)



b

= range(1,8)


c

= range(0,14,3)


d

= range(8,1,
-
1)


Conditional Statements (1)

The if statement:


if

test
:




...


elif

test
:




...


else:




...


The usual comparison operators for testing:

<, >, ==, !=, <=, >=


They work on most Python objects

The while statement:

while
test
:


...


Conditional Statements (2)


if statement example:

if
a
==

5
:


print "It's five!"

elif

a == 6
:


print "It's six!"

else:


print "It's something else.”



while statement example:

a = 0

while

a
<

3
:


a = a +1


print "Counting up to 3..."

Play Around 4


Write a short
prog

in python which prints uses the local time
to print something.


Hint: module time,
time.localtime
(), to get the hours
mytime.tm_hour
()


import time

now =
time.localtime
()

hour =
now.tm_hour


if hour < 8: print 'sleeping'

elif

hour < 9: print 'commuting'

elif

hour < 17: print 'working'

elif

hour < 18: print 'commuting'

elif

hour < 20: print 'eating'

elif

hour < 22: print 'resting'

else: print 'sleeping'

Regular Expressions


Import the
re
package to use regular expressions


re's

must
be compiled into an object


A number of functions are available in a compiled re:

match
()

search
()

split
()

sub
()

. . .


For more information see the documentation

pydoc

re


Regular Expressions


Write a short
prog

in python, which match a re to validate a list of
phone number


Hint: import re module,
re.match

(filename),
glob.glob
('*.
py
')



import
re


for
test_string

in ['555
-
1212', 'ILLEGAL']:

if
re.match
(
r'^
\
d{3}
-
\
d{4}$',
test_string
)
:



print
test_string
, '
is a valid US phone number
'


else:



print
test_string
, 'rejected
'

Play Around


Write a short
prog

in python, which open a file and prints its
content



Hint: use glob module, open (filename),
glob.glob
('*.
py
')



import glob

# glob supports Unix style pathname extensions

python_files

=
glob.glob
('*.
py
')

for fn in
sorted(python_files
):

print '
------
', fn

for line in
open(fn
):


print ' ' +
line.rstrip
()

print


Functions (1)


functions can be defined using def

def

fib
(
n
):

# calculate
fibonacci

up to
n

...


arguments can have default values through
assignment in the definition

def
fib(
n
=100
):

#
n

has default value 100

..
.

Function (2)


Return values

use the return statement to have a function return a value

without a return value a function returns None





Example

def

fib
(
n
):

# return Fibonacci series up to
n



result = []



a,
b

= 0, 1



while
b

<
n
:




result.append(b
)


# see below




a,
b

=
b
,
a+b


return result

Function (2)


Usage


calling the example function without an argument



>>> fib() # call it



[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]



calling the example function with an argument



>>> fib(50) # call it again



[1, 1, 2, 3, 5, 8, 13, 21, 34]

Play Around 5


Write a short
prog

in python which has a function
with greets the name given as arguments


def
greet(name
):

print 'hello', name


greet('Jack
')

greet('Jill
')

greet('Bob
')

Play Around 6


Write a short
prog

in python which sum up integers in
the command line


Hint: important sys module, try: … except
ValueError
:


#!/
usr/bin/env

python

import sys


try:

total =
sum(int(arg
) for
arg

in sys.argv[1:])

print 'sum =', total

except
ValueError
:


print 'Please supply integer arguments'


Modules (1)


A module is a file
containing Python definitions
and
statements.


The
file name
is the
module name
with the
sux

.
py

appended.


Within a module, the module's name (as a string) is
available as the value of the global variable
__name__
.

Modules (2)


Example module
fibo
.py



# Fibonacci numbers module


def
fibo
(n
):



# write Fibonacci
series up to
n




a,
b

= 0, 1




while
b

<
n
:





print
b





a,
b

=
b
, a +
b

Modules (3)



Import
the module with the following command:


>>>
import

fibo


The functions are
not included
directly


Using the module name you can access the
functions:


>>> fib.fibo(1000)


1 1 2 3 5 8 13 21 34 55 89 144 233 377
610 987


>>>
fibo.
__name
__


'
fibo


Modules (4)


If you intend to use a function often you can assign it
to a local name:


>>> fib =
fibo.fib


>>> fib(500)


1 1 2 3 5 8 13 21 34 55 89 144 233 377

Modules (5)


The built
-
in function dir() can be used to find out
which names a module defines
. It returns a sorted
list of strings:


>>> import
fibo


>>>
dir(fibo
)


['__name__', 'fib']



It lists
all types of
names:
variables
,
modules
,
functions
, etc.


Without arguments, dir() lists the names you have
defined currently

Packages (1)


Packages are a way of
structuring Python's module


namespace by using
dotted

module names".


They
hide module names
from other packages


They
are made up
of modules in a particular
hierarchic file system


Each directory name is apart of the module structure

Packages (2)


An example Package:

Sound/







Top
-
level package




__
init__.py




Initialization




Formats/





file format
conversions






__
init__.py






wavread.py






...




...


The
__
init__.py

files are required to make Python
treat the directories as containing packages why?


__
init__.py

can just be an empty file, but it can also
execute initialization code for the package.

Packages (3)


Import individual modules from the package:

import
Sound.Effects.echo



Any functions
in a package
must
still be
referenced
by their
fully qualified name





Sound.Effects.echo.echofilter
( ... )





An alternative way of importing the
submodule

is:

from
Sound.Effects

import
echo



This also loads the
submodule

echo, and makes it available without its package
prex

(
Sound.Effects
).



echo.echofilter
( ... )



Import all modules from the package:

from
Sound.Effects

import *

Class Objects


class
definitions
introduce
new a namespace, with its
OWN
scope



all definitions within a class definition are in that new scope



classes can be
instantiated
into
instance objects



the
first
argument
of a
function within a class
is
an object
reference

to a class instance



Example


class
MyClass
:




i

= 12345




def
f(
self
):





return 'hello world’

Instance Objects (1)


Class instantiation uses
function

notation:


x

=
MyClass
()
# It creates a new
instance
of
















# the
class
and
assigns this
















# object to
the local variable
x
,
















# which

now represents an instance
















# object.


A class may define a special
method named
__init__
()

for
initialization:



def __
init__(self
):




self.data

= []

Instance Objects (2)


You can create and delete attributes from an instance
object (not from a class object)


create by
assignmen
t


delete by using
del
.



x
.counter

=

1


while
x
.counter

< 10:




x
.counter

*= 2


print
x
.counter


del
x
.counter

Method Objects


Method objects

are
instantiations
of
functions
in a
class
.



the call
x.f
()

is exactly equivalent to
MyClass.f(x
)


The
first
argument
is always the
object itself
, in this case
x
.


Method objects can be stored separately for later use



xf

=
x.f


while True:



print
xf
()

Example of class

class
BankAccount(
object
):

def
__
init__
(self
,
initial_balance
=0):



self.
balance

=
initial_balance


def
deposit
(self
, amount):



self.balance

+= amount

def
withdraw
(self
, amount):



self.balance

-
= amount

def
overdrawn
(self
):



return
self.balance

< 0



my_account

= BankAccount(15)

my_account
.withdraw(5)

print
my_account
.balance


Documentation



BOOKS!, they are in the back of the classroom. . .


Use the web, there are a lot of websites on python


Check
www.python.org

for help.


Use the
pydoc

tool, python manual pages etcetera.


Material for these slides was taken from

http://
www.python.org
/doc

Assignment


Create a class for keeping track of the various hardware
configuration and their relation to each other as used in our Lab.
Note that there are different types of hardware and relations.



So, define a number of types of hardware and a number of types if
relations (direct cable network, etc) and create a single class that
can be instantiated to represent each and every one of them. The
instance objects must be connected through relations to represent
, in the end , the OS3 Lab in an abstract sense. So the objects
represent a tree structure representing the lab as whole .



So as an example: your desktop machine has a keyboard a mouse
and two screens directly attached to it. The desktop computer itself
is connected to the experimentation machines through a network.
Then describe the experiment machines etc, etc.

Assignment


The following functions must be made available for each node or piece of
hardware




Print (or
dtr/repr
)


should print the info of the certain piece only


this includes the hardware description at least. You could only also include it’s
position tin the lab/server room, its color etc.


Printall


Should print he information for this piece and all its descendant



this should traverse the object downwards only


Bonus


Thinks of way to create and a actual description of the lab on top of the
abstract description, so; add the name of a computer and who sits behind
it etc. this implies that there can be many desktops computer instances
that look exactly the same hardware wise, but have different owners.