Python Fundamentals: Scripting Languages
Python Fundamentals: Scripting Languages
Scripting Languages
References
• http://www.linuxjournal.com/article/3882 “Why Python?” by Eric
Raymond in the Linux Journal, May 1st 2000.
• http://www.geeksaresexy.net/2008/07/25/the-ascent-of-scripting-l
anguages/
“The ascent of scripting languages” by Chip. July 25, 2008.
From the site Geeks are Sexy ™
• Python tutorial:
• Python web page: http://www.python.org/
What is a Scripting Language?
• Wikipedia: A scripting language, script
language or extension language, is a
programming language that controls a
software application. "Scripts" are often
treated as distinct from “programs", which
execute independently from any other
application.
Early Scripting Languages
• Controlled the actions of system programs
• Job Control Language (JCL):controlled batch job
executions on IBM mainframes
• Shell scripts: A series of instructions to the shell,
or command line interpreter, of a UNIX system
• When used like this, scripting languages take
pre-existing components, maybe in different
languages, and combine them so they work
together.
Example Shell Script
from Ousterhout
• select | grep scripting | wc
where
– select is a program to read and output the text
that is currently selected on the display
– grep is a program reads input and outputs the
lines containing "scripting";
– wc is a program to count the lines in its input.
– “|” is the pipe command that directs the output
from one program to the input of the next
program.
Modern Scripting Languages
• Perl, Python, Ruby, …
• More like a traditional programming
language than early scripting languages.
• Higher level in the sense that programmers
don’t have to worry about many of the
details that are a part of C-like languages
– No explicit memory allocation/deallocation, for
example
Modern Scripting Languages
• It’s possible to write full-featured programs
in these languages
• Used frequently today for “quick-and-dirty”
programming –
– Quick results
– Small programs
• See next definition
What is a Scripting Language?
• "scripting language." Encyclopædia Britannica. 2008.
Encyclopædia Britannica Online. 30 Sep. 2008 <
http://www.britannica.com/EBchecked/topic/1086439/scri
pting-language
>.
• “Scripting languages are sometimes called little
languages. They are intended to solve relatively small
programming problems that do not require the overhead
of data declarations and other features needed to make
large programs manageable. Scripting languages are
used for writing operating system utilities, for special-
purpose file-manipulation programs, and, because they
are easy to learn.”
Scripts are Usually Interpreted
• Using an interpreter instead of a compiler
makes sense when programs change
frequently and/or are very interactive.
– Reason: no extra compile time
• In the scripting language-as-glue-language
mode, performance is dominated by the
modules being connected by the scripting
commands
Why Python?
• No universal agreement on which scripting
language is best
• Perl, Ruby, others also have advocates
• Perl: good for system administration
duties, traditional scripting
– Awkward syntax, OO as an afterthought, less
readable than other languages
• Python – has attracted many former Perl
users
Python - Intro
• Python is a general purpose language that
implements the imperative, object-oriented, and
functional paradigms.
• Dynamic typing, automatic memory management,
exceptions, large standard library, modular.
– Extensions can be written in C and C++
– Other language versions (Jython, IronPython) support
extensions written in Java and .Net languages)
• Design philosophy: easy to read, easy to learn
Versions
• Production versions are 2.6.4 and 3.1.1
• Both versions are stable and suitable for use
• Python 2: compatible with more existing
software
• Python 3: a major redesign
– Not backward compatible.
– Most features are the same or similar, but a few will
cause older programs to break.
– Part of the Python philosophy – don’t clutter up the
language with outdated features
• Write your programs to run in the CS lab (v 3.1).
Interesting Features
• White space does indicate meaning
– Instead of curly brackets or begin-end pairs,
whitespace is used for block delimiters.
• No variable declarations
• Dynamic typing
• Associative arrays (dictionaries)
• Lists and slices
Execution Modes
Calculator mode: type in an expression,
Python will evaluate it:
>>> a = 5
>>> b = 10
>>> a+b
15
Dynamic change of type
>>> a = 'horse’
>>> a = ‘ cart’
>>> a + b
‘horse cart’
Execution Modes - Program
#factorial.py
# compute the factorial of a number
def main( ):
n = input(“enter a whole number”)
fact = 1
for factor in range (n, 1, -1)
fact = fact * factor
print “the factorial of”, n, “is”,fact
main( )
Program Elements
• Identifiers:
– Must begin with letter or underscore, followed by any
number of letters, digits, underscores
• Variables:
– Do not need to be declared
– A variable is created when a value is assigned to it:
Examples: num = 3
– Can’t be used in an expression unless it has a value
– Error message: Name Error – means no value is
associated with this name
Variables
• Variable names don’t have types – values
(or objects) do
– A variable name has the type of the value it
currently references
• Variables actually contain references to
values (similar to pointers).
– This makes it possible to assign different
object types to the same variable
Variables contain references to data values
A 3.5
A=A*2 A 3.5
A = “cat”
7.0
cat
Python handles memory management automatically. It will
create new objects and store them in memory; it will also
execute garbage collection algorithms to reclaim any
inaccessible memory locations.
0 1 2 3 4 5 6 7 8 9
0 1 2
>>> for i in range(5,10):
print i,
5 6 7 8 9
>>> for i in range(6,12,2):
print i
6
8
10
Ranges can also be specified using
expressions:
>>> n = 5
>>> for i in range(2*n +3):
print i,
0 1 2 3 4 5 6 7 8 9 10 11 12
Using a List in a for loop
Lists are enclosed in square brackets
3 2 1
>>> for i in ['cat', 'dog', 'elephant']:
print i,
J o e S m i t h
Lists
• A list is a comma-separated sequence of
items, enclosed in square brackets
• Lists can be heterogeneous – items don’t
have to be from the same data type
• Like strings, lists can be sliced, indexed,
concatenated, and repeated.
• The len() function will return the number
of elements in the list
>>> myList = ['milk','eggs','bread',10]
>>> myList[0:3]
['milk', 'eggs', 'bread']
>>> x, y, z = 3, 5, 9
>>> yourList = [x, y, z, "018"]
>>> yourList[0:2]
[3, 5]
>>> 2 * myList[1:2]
['eggs', 'eggs']
>>> len(myList)
4
>>> yourList[:8] #try to exceed length
[3, 5, 9, '018']
Lists
• Unlike strings, lists are mutable (can be
changed)
– Make an assignment, using the index
>>> myList[1] = 'butter'
>>> myList
['milk', 'butter', 'bread', 100]
• You can also assign to slices, and even
change the length of the list
List Slice Operations
#create a list
>>> data = ['bob', 32, 'sue', 44]
>>> data
['bob', 32, 'sue', 44]
#assign to a list slice
>>> data[1:3] = ['dave', 14]
>>> data
['bob', 'dave', 14, 44]
#insert an element
>>> data[1:1] = [19]
>>> data
['bob', 19, 'dave', 14, 44]
#delete an element
>>> data[3:4] = []
>>> data
['bob', 19, 'dave', 44]
Sequences
• Strings and lists are both sequences.
• Sequence operations include
<seq>+<seq> concatenation
<seq> * (int-exp> repetition
<seq>[ ] indexing
<seq>[ : ] slicing
len(<seq>) length
for <var> in <seq> iteration
Nested Lists
>>> grades = [100, 97, 85]
>>> stRec = ['A000','jack',grades]
>>> stRec
['A000', 'jack', [100, 97, 85]]
>>> len(stRec)
3
More About Lists
• See Section 5.1 in the Python tutorial to
get a whole set of list functions:
– append(x)
– insert(i, x)
– etc.
• Since lists are objects, dot notation is used
to call the functions
More Examples
>>> stRec.remove(grades)
>>> stRec
['A000', 'jack']
>>> stRec.append([100, 97, 85])
>>> stRec
['A000', 'jack', [100, 97, 85]]
>>> stRec.pop(2)
[100, 97, 85]
>>> stRec
['A000', 'jack']
Dictionaries
• Also called associative arrays
• Resemble hash tables
• Unlike sequences (lists, strings) which are
indexed sequentially, dictionaries are an
unordered collection of key-value pairs.
• Items are retrieved according to their keys.
• See Section 5.5 in the tutorial for more
examples
>>> roll = {1023: 'max', 0404: 'sue'}
>>> roll[1023]
'max'
>>> roll[9450] = 'alice'
>>> roll
{9450:'alice', 260:'sue', 1023:'max'}
>>> roll.keys()
[9450, 260, 1023]
>>> roll.has_key(2600)
False
>>>
Python Functions
• A Python function can be either void or
value returning, although the definition isn’t
identified as such.
– Technically, they are all value returning, since
a void function returns the value none
• Each function defines a scope. Parameters
and local variables are accessible in the
scope; values in other functions are
available only as parameters.
Function Syntax
Function definition
def <name> (formal-parameters>):
<body>
def main( ):
print "a chaotic function"
x = input("enter a number between 0 and 1: ")
for i in range (10):
x = 3.9 * (1 - x)
print x
y = input("Press any key to exit ")
main()
Functions That Return Values
>>> def sum(x, y): >>> def SumDif(x,y):
sum = x + y sum = x + y
return sum dif = x - y
return sum, dif
>>> num1,num2 = 3,79
>>> sum(num1, num2) >>> a,b = SumDif(x,y)
82 >>> a
17
>>> print a, b
17 -3
>>>
Parameters
• Parameters are passed by value, so in
general the actual parameters can’t be
changed by the function – only their local
copies
• Mutable objects (e.g., lists) act like
reference parameters
– the value passed is a pointer to a list of
pointers, and these pointers remain the same;
only the things pointed to change!
– (don’t worry about the subtleties here)
Lists and Strings – Review
• Strings are sequences of characters, lists
are sequences of individual items
– aStr: “47^abc”
– aList: [‘sue’, 479, 3.7, ‘tree’]
• String elements and list elements can be
accessed by an index
• String elements can’t be changed in place;
list items can be.
Common Operations
• Slicing
• Concatenation & repetition
• Indexing
• Applying the length function :
– len(aList) or len(aStr)
• Iteration through elements
– >>> for i in range(len(myStr)):
print myStr[i]
– >>> for i in range(len(myStr)):
print myStr[i]
Additional String Operations
• split: divides a list into a list of substrings
– >>> myStr = 'The fat black cat‘
>>> myStr.split()
['The', 'fat', 'black', 'cat']
• split defaults to blank as the delimiter,
but you can specify a different character:
>>> myStr = '12/10/2008'
>>> myStr.split('/')
['12', '10', '2008']
Strings – Continued
• When using string functions begin by
importing the string library:
– import string
• After you have split a string into a list of
substrings, you may want to convert some
of the substrings to specific data types. The
generic function is eval(<string>) and there
are specific casts: int( ), float( ), long( ), and
str( ).
Example
>>> x = myStr.split('/')
>>> x
['12', '10', '2008']
>>> print eval(x[0]),int(x[1]),float(x[2])
12 10 2008.0
File I/O
• <filevar> = open(<name>, <mode>)
where name is the name of the file on disk, and
mode is either ‘r’ or ‘w’
– infile = open(“data.in”, “r”)
– outfile = open(“data.out”, “w”)
• Files must also be closed:
– infile.close( )
– outfile.close( )
Input Operations
• <filevar>.read: returns the remaining
contents of the file as a multi-line string (lines in
the file separated by \n)
• <filevar>.readline( ): returns next line
as a string; includes the newline character (you
can slice it off, if needed)
• <filevar>.readlines( ): returns the
remaining lines in the file, as a list of lines (each
list item includes the newline character)
Input/Output
• Output operations are less flexible, the
only parameter is a string.
– If you want to put a newline character in the
file you must do so specifically
• Output formatting: % character
• <template-string> % (<value>)
• Possible formats are d (decimal), f (float)
and s (string)
Example
>>> outfile=open("C:\Temp\exmp.out",
"w")
>>> outfile.write("this is the first
line\n")
>>> outfile.write('and this is the
second\n')
>>> outfile.write("the value of x is
%d and y is %f" % (x, y))
>>> outfile.close()