Docsity

Scripting Languages and Python: Parameter Passing Mechanisms and Scoping Rules - Prof. Ana, Study notes of Programming Languages

Toggle sidebar
bg1
1
Spring 09 CSCI 4430, A Milanova/BG Ryder 1
Announcements
HW4
Due Tuesday, April 14th
Project 3: Python and Java
Will be posted April 14th
Due April 28th
Python infrastructure
FreeBSDs, or download from www.python.org
Java infrastructure
FreeBSDs, or download an IDE such as Eclipse
Spring 09 CSCI 4430, A Milanova/BG Ryder 2
Announcements (ii)
A slight change in schedule
Today:
Scripting Languages and Python
From next class on:
Object-oriented programming
Java
Concurrency in Java
Spring 09 CSCI 4430, A Milanova/BG Ryder 3
Announcements (iii)
Final Exam: May 5th 3-6pm
Final Exam Topics
Exam is cumulative
About 40% on pre-midterm material
About 60% on remaining material
Functional programming and Scheme (Sc10)
Lambda calculus
Data abstraction: Types (Sc7.1 –7 .7.1)
Control abstraction: Parameter Passing (Sc8.1-8.3)
Scripting languages and Python (TBD)
Object-oriented languages and Java (TBD)
Concurrency (TBD)
Comparative programming languages
Spring 09 CSCI 4430, A Milanova/BG Ryder 4
Last Class: Parameter Passing
Parameter Passing Mechanisms
Call by value
Call by reference
Call by result
Call by value-result
Call by name
Scripting Languages
Python
Read (Optional): Scott,
Chapter 13
5Spring 09 CSCI 4430, A Milanova/BG Ryder 6
Topics
Scripting Programming Languages
Taking Stock: PL Design Choices
Python
Syntax and scoping
Datatypes
Control flow constructs
The “Python Style”
Modules
os and re modules
pf3
pf4
pf5
pf8

Partial preview of the text

Download Scripting Languages and Python: Parameter Passing Mechanisms and Scoping Rules - Prof. Ana and more Study notes Programming Languages in PDF only on Docsity!

Spring 09 CSCI 4430, A Milanova/BG Ryder 1

Announcements

 HW

 Due Tuesday, April 14th

 Project 3: Python and Java

 Will be posted April 14th

 Due April 28th

 Python infrastructure

 FreeBSDs, or download from www.python.org

 Java infrastructure

 FreeBSDs, or download an IDE such as Eclipse

Spring 09 CSCI 4430, A Milanova/BG Ryder 2

Announcements (ii)

 A slight change in schedule

 Today:

 Scripting Languages and Python

 From next class on:

 Object-oriented programming

 Java

 Concurrency in Java

Spring 09 CSCI 4430, A Milanova/BG Ryder 3

Announcements (iii)

 Final Exam: May 5th^ 3-6pm

 Final Exam Topics

 Exam is cumulative

 About 40% on pre-midterm material

 About 60% on remaining material

 Functional programming and Scheme (Sc10)

 Lambda calculus

 Data abstraction: Types (Sc7.1 – 7.7.1)

 Control abstraction: Parameter Passing (Sc8.1-8.3)

 Scripting languages and Python (TBD)

 Object-oriented languages and Java (TBD)

 Concurrency (TBD)

 Comparative programming languages

Spring 09 CSCI 4430, A Milanova/BG Ryder 4

Last Class: Parameter Passing

 Parameter Passing Mechanisms

 Call by value

 Call by reference

 Call by result

 Call by value-result

 Call by name

Scripting Languages

Python

Read (Optional): Scott,

Chapter 13

5

Spring 09 CSCI 4430, A Milanova/BG Ryder 6

Topics

 Scripting Programming Languages

 Taking Stock: PL Design Choices

 Python

 Syntax and scoping

 Datatypes

 Control flow constructs

 The “Python Style”

 Modules

 os and re modules

Spring 09 CSCI 4430, A Milanova/BG Ryder 7

Scripting Programming Languages

 E.g., Perl, Tcl, Python, Ruby, VBScript, AppleScript

 Originate in the 1970’s from UNIX (shell scripts)

 Purpose

 To process text files with ease

 To launch components and combine (or “glue”) these

components into an application

 Characteristics

 Ease of use, flexibility, rapid prototyping: hence, scripting

languages are dynamically typed

 Extensive support for text processing

Spring 09 CSCI 4430, A Milanova/BG Ryder 8

Python

 Designed by Guido van Rossum at CWI,

Amsterdam in early 1990’s

 Multi-paradigm programming language

 All characteristics of scripting languages

 It has “functional” features

 E.g. higher-order functions, list comprehensions

 It has “object-oriented” features

 E.g., iterators, array slicing operations, reflection,

exceptions, (multiple) inheritance, dynamic loading

Spring 09 CSCI 4430, A Milanova/BG Ryder 9

Taking Stock: Design Choices

Assignment

statement

Conditional flow,

Iteration,

Method calls

Primitive types,

struct types,

pointer types,

Classes

C++

Assignment

statement

Conditional flow,

Iteration,

Method calls

Primitive types,

Classes (library,

and user-defined)

Java

Function

application

Conditional flow,

Recursion

Numbers,

Symbols,

Lists

Scheme

Datatypes Control-flow Basic Operation

Spring 09 CSCI 4430, A Milanova/BG Ryder 10

Taking Stock: Design Choices (ii)

C++

Java

Scheme

Variable Model

Parameter Passing Mechanism

Scoping Typing

Reference model

Value model for simple types, reference model for class types

Value model

By Value

By Value

By value and by reference

Static, nested function definitions

Static, no nested function definitions

Static, no nested function definitions

Dynamic, strong

Static, strong

Static, weak

Spring 09 CSCI 4430, A Milanova/BG Ryder 11

Syntax and Scoping

m=1; j=

def outer():

def middle(k):

def inner():

global m; # from main program, not outer

m=4;

print m,j,k;

inner()

return m,j,k # 3 element tuple

m=2; # new local m

return middle(j) # old (global) j

print outer()

print m,j

Scott p 725

Variable belongs to block where it is

written, unless explicitly imported.

What is the output of this program?

What’s printed if we remove

the red “global m” statement?

the blue assignment statement?

Spring 09 CSCI 4430, A Milanova/BG Ryder 12

Scoping: Common Indentation Error

… ~/python>python scope.py

File "scope.py", line 10

m=2; #new local m

^

IndentationError: unindent does

not match any outer indentation

level

Spring 09 CSCI 4430, A Milanova/BG Ryder 19

Datatypes: Tuples

 Tuples

 Immutable!

 Similar to lists, except that it is immutable

 E.g., (1, ’john’, 3, ’mary’)

 Operations

 As on string: +, *, [j], [j:k], len(), for x in L

Spring 09 CSCI 4430, A Milanova/BG Ryder 20

Datatypes: Dictionaries

 Dictionaries (also called associative arrays)

 E.g.,

d = {'apples':10,'oranges':5,'pears':1,'tangerines':2}

 Operations

 d.values()

 d.keys()

 d.has_key(‘apple’)

 Etc.

Spring 09 CSCI 4430, A Milanova/BG Ryder 21

Datatypes: Dictionaries (ii)

d = {'apples':10,'oranges':5,'pears':1,'tangerines':2};

print d['oranges'];

print d; #{'tangerines':2,'pears':1,'apples':10, 'oranges':5}

print d.keys(); #['tangerines', 'pears', 'apples', 'oranges']

print d.values(); #[2, 1, 10, 5]

print d.has_key('pears'); #True

print d.has_key('apricot'); #False

print d; #{'tangerines': 2,'pears':1,'apples':10,'oranges':5}

d['pears']=6;

print d; #{'tangerines':2,'pears':6,'apples':10,'oranges':5}

del d['apples'];

print d; #{'tangerines': 2, 'pears': 6, 'oranges': 5}

print len(d);

Spring 09 CSCI 4430, A Milanova/BG Ryder 22

Datatypes: Dictionaries (iii)

z = {'apples':4, 'plums':2}; z.update(d); #note overwrite of apples value from d print z; #{'oranges':5,'pears':6,'plums':2,'apples':10,'tangerines': 2} #print out table by iterating over its keys set #oranges 5 #pears 6 #plums 2 #apples 10 #tangerines 2 for fruit in z.keys(): print fruit, '\t', z[fruit];

23

Datatypes: Files

#practice with file objects output = open('/cs/milanova/python/temp', 'w'); input = open('/cs/milanova/python/intemp', 'r'); input2 = open('/cs/milanova/python/intemp', 'r'); s = input.read(); print s; #this is a file of sentences #to be used as data for a python program #Ana t=input2.readline(); print t; #this is a file of sentences

t=input2.readline(); print t; #to be used as data for a python program

output.write(s); output.close(); Spring 09 CSCI 4430, A Milanova/BG Ryder^24

Dataypes: Files (ii)

Myfile = open(‘myfile’’w’); Myfile.write(‘hello world\n’); Mufile.close(); Myfile = open(‘myfile’,’r’); Myfile.readline(); #hello world Myfile.readline(); #‘’ empty string means end of file

Spring 09 CSCI 4430, A Milanova/BG Ryder 25

Datatypes

 So, what model for variables does Python use?

 Reference model for variables

 May have result in unexpected values due to aliasing

 Equality

 == equal in value (structural equality, value equality)

 is same object (reference equality)

 None acts like null in C, a placeholder for an actual value

Spring 09 CSCI 4430, A Milanova/BG Ryder 26

Datatypes: Common Errors

 Updates to shared references

 A=[1,2]; B=[1,A]; A[1]=0 changes B also!

 Repetition results may be unexpected

 L=[4,5,6]; X = L3; Y=[L]3 makes X

[4,5,6,4,5,6,4,5,6] and makes Y [[4,5,6][4,5,6][4,5,6]]

 Cyclic data structures

 L = [‘hello’]; L.append(L); L becomes [‘hello’,[…]]

 Immutable types cannot be assigned to

 T = (1,2); T[1]=-4 #ERROR; T=T[:1]+(4,) #OK

Spring 09 CSCI 4430, A Milanova/BG Ryder 27

Control Flow

 Short-circuit evaluation of boolean expressions

 Constructs for conditional control flow: if

if x==‘Ana’: if z==1:

print ‘found Ana’ a=

elif x==‘Mary’: if y==2:

print ‘found Mary’ print “y is 2”

else: print “z is 1”

print ‘missing key’ print ‘done’

Spring 09 CSCI 4430, A Milanova/BG Ryder 28

Control Flow (ii)

 Constructs for looping: while

x= y/

while x>1: #matches else below;shown by indenting

if y%x==0:

print y, ‘has factor’, x

break #skips the else

x = x-

else: #is executed even if loop body isn’t

print y, ‘is prime’

Spring 09 CSCI 4430, A Milanova/BG Ryder 29

Control Flow (iii)

 Constructs for looping: for

for x in [“spam”, “eggs”, “ham”]:

print x #iterates over list elements

s = “lumberjack”

for y in s: print y #iterates over chars

 Comments delimited by # anywhere on a line

30

Functions

 Two forms of function definition

def incr(x): return x+1 #function incr #list of 2 functions incrs = [lambda x: x+1, lambda x: x+2]

 Polymorphism

#what datatypes can this function be used on? def intersect(seq1, seq2): res = [ ] for x in seq1: #iterates over elements in seq if x in seq2: #checks if element is in seq res.append(x) #if so, adds element to list return res

print intersect([1,2,3],[2,4,6]) #[2] print intersect( (1,2,3,4), (4,3,5)) #[3,4] print intersect( (1,2,3), [1,2,3]) #[1, 2, 3] print intersect({1:'a',2:'b',3:'c'}, {1:'a',4:'d'}) #[1] print intersect({1:'a',2:'b',3:'c'}, {4:'a',5:'b'}) #[] #clearly the intersection is on the keys, not the values!

Spring 09 CSCI 4430, A Milanova/BG Ryder 37

How to walk a directory (ii)

#root= /cs/milanova/python/testHandin

#diry= Prolog Scheme Python

#files=

#root= /cs/milanova/python/testHandin/Prolog

#diry= peter ana

#files=

#root= /cs/milanova/python/testHandin/Prolog/peter

#diry=

#files= proj1 proj

#root= /cs/milanova/python/testHandin/Prolog/ana

#diry=

#files= file2 file

Spring 09 CSCI 4430, A Milanova/BG Ryder 38

How to walk a directory (iii)

#root= /cs/milanova/python/testHandin/Scheme

#diry= ana katarina

#files=

#root= /cs/milanova/python/testHandin/Scheme/ana

#diry=

#files= file1 file2 file

#root= /cs/milanova/python/testHandin/Scheme/katarina

#diry=

#files= project

#root= /cs/milanova/python/testHandin/Python

#diry=

#files=

Spring 09 CSCI 4430, A Milanova/BG Ryder 39

Regular Expressions in Python

 re module – regular expression functionality

 Pattern constructors

. Matches any char ^ Matches beginning of string $ Matches end of string (just before \n)

  • 0 or more repetitions of preceding regular expression
  • 1 or more repetitions of preceding regular expression ? Matches 0 or 1 of preceding regular expression [ ] delimits a set of characters as possible matches [a-zA-Z] matches any alphabetic symbol

[^a-z] matches any non-alphabetic symbol

| A|B where A,B are regular expressions, means A or B matches tried from left to right in | expression \s matches any whitespace character \d matches [0-9]

Spring 09 CSCI 4430, A Milanova/BG Ryder 40

Suppose you have a list of addresses and you want to convert the street

address to use abbreviations for 'Avenue' (Ave.), 'Road' (Rd.), and Street

(St.); how to do this with regular expressions in Python

import re #RE module f1=open("/cs/milanova/python/addrs.in") f2=open("/cs/milanova/python/addrs.out") for line in f1: #$ in pattern means end of string x = re.sub(r'ROAD$', 'Rd.',line) print line, x for line in f2:

x = re.sub('\bROAD$', 'Rd.', line) #\b requires word

to start at this point

y = re.sub(r'\bROAD$', 'Rd.', line) #r is raw string

mode, to prevent any escapes due to backslashes.

z = re.sub(r'\bROAD\b', 'Rd.', line) #new pattern does

not require ROAD to be at end of string

print line,x,y,z

Ex1-simple substitution, addrs.py Cf Dive into Python

Spring 09 CSCI 4430, A Milanova/BG Ryder 41

Input

100 BROAD ROAD

100 FALLS ROAD, Apt 10 100 FALLS ROAD, 101 FALLS ROAD

Output (excerpts)

100 BROAD ROAD

100 BROAD Rd. #pattern worked and didn’t change ROAD in BROAD 100 FALLS ROAD, Apt 10 100 FALLS ROAD, Apt 10 #pattern failed 100 FALLS ROAD, 101 FALLS ROAD 100 FALLS ROAD, 101 FALLS Rd. #pattern worked on last ‘ROAD’ … 100 FALLS ROAD, 101 FALLS ROAD 100 FALLS ROAD, 101 FALLS Rd. 100 FALLS ROAD, 101 FALLS Rd. 100 FALLS Rd., 101 FALLS Rd.

addrs.out

Cf Dive into Python

Spring 09 CSCI 4430, A Milanova/BG Ryder 42

import re

s = 'cabcd'

t = 'aabbaabb'

print s,t #cabcd aabbaabb

patt = re.compile(r'^a+') #creates pattern

x = patt.search(s) #searches for pattern in string s

if x != None: #if no match, returns None

print x.group() #else print what matched pattern

print (patt.search(t)).group() #aa

patt2 = re.compile(r'a+')

print (patt2.search(s)).group() #a

print (patt2.search(t)).group() #aa

for matchObj in patt2.finditer(t):

print matchObj.end() #prints 2 and 6

Ex2- forming and using patterns and matches

Spring 09 CSCI 4430, A Milanova/BG Ryder 43

patt3=re.compile(r'(?Pa+)|(?Pb+)')

print (patt3.search(s)).group("x1")#a

print (patt3.search(s)).group("x2")#None

for matchObj in patt3.finditer(t):

print matchObj.end() #prints 2,4,6,

Ex2- forming and using patterns and matches