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

Python Fundamentals: Scripting Languages

Uploaded by

wald007
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views

Python Fundamentals: Scripting Languages

Uploaded by

wald007
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 63

Python Fundamentals

Scripting Languages
References
• http://www.linuxjournal.com/article/3882 “Why Python?” by Eric
Raymond in the Linux Journal, May 1st 2000.

• http://www.tcl.tk/doc/scripting.html “Scripting: Higher Level


Programming for the 21st Century”, John K. Ousterhout, IEEE
Computer, March 1998.

• 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.

Python does not implement reference semantics; if A = 10


and B = A, A = A + 1 does not change the value of B
Expressions
• An expression calculates a value
• Arithmetic operators: +, -, *, /, **
(exponentiation)
• Add, subtract, multiply, divide work just as
they do in other C-style languages
• Spaces in an expression are not significant
• Parentheses override normal precedence
Output Statements
• Statement syntax: (EBNF notation)
print {expression,}
where the final comma in the list is optional
• Examples:
print # prints a blank line
print 3, y, z + 10 # go to new line
print “the result is” z,# no new line
• Output items are automatically separated by a
single space.
Assignment Statements
• Syntax: Assignment → variable = expression
• A variable’s data type is determined by the type of the value
assigned to it.
• Multiple_assign →var{, var} = expr{, expr)
>>> x, y = 4, 7
>>> x
4
>>> y
7
>>> x, y = y, x
>>> x
7
>>> y
4
>>>
Input
• Syntax: input → variable = input(string)
The string is used as a prompt.

>>> y = input("enter a name ")


enter a name "max"
>>> y
'max'
>>> number = input("Enter an integer ")
Enter an integer 32
>>> number
32
>>> thing = input("enter an expression ")
enter an expression 3 * 8 / 4
>>> thing
6
Input
• The input statement can be part of a multiple
assignment statement:

>>> x, y = input("enter two comma-separated


values: ")
enter two comma-separated values: 13, 26
>>> x
13
>>> y
26
Input
• The raw_input function is another way to
read string data
– No need to quote the input strings
>>> s = raw_input("Enter a sentence ")
Enter a sentence Python is easy!
>>> s
'Python is easy!'
>>>
Raw_input versus input
• raw_input reads everything as a string
• Using raw_input is a safety measure for
reading data – use a cast to get correct
type, if necessary
r = float(raw_input(“enter radius”))

• Now, if user enters something inappropriate,


Python will throw an exception.
Python Control Structures
• Python loop types:
– while
– for
• Decision statements:
– if
• Related features:
– range( ) # a function
– break # statements similar to
– continue # those in C/C++
General Information
• The first statement in the body of a loop
must be indented.
• All other statements must be indented by
the same amount
• To terminate a loop body, enter a blank
line.
While Loop
>>> x = 0
>>> while (x < 10): #remember semicolon!
print x, #prints on one line
x = x + 1

0 1 2 3 4 5 6 7 8 9

Conditions are evaluated just as in C/C++: 0 is


false, non-zero is true
The conditional operators are also the same
Note indentation – provided by the IDLE GUI
For Loops
• Syntax:
for <var> in <sequence>:
<body>
• <sequence> can be a list of values or it
can be defined by the range( ) function
– range(n) produces a list of values: 0, 1, …,n-1
– range(start, n): begins at start instead of 0
– range(start, n, step): uses step as the
increment
>>> for i in range(3):
print i,

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

>>> for i in [3, 2, 1]:


print i,

3 2 1
>>> for i in ['cat', 'dog', 'elephant']:
print i,

cat dog elephant


If Statement
• Python if statement has three versions:
– The if (only one option)
– The if-else (two options)
– The if-elif-else (three or more options)
• The if-elif-else substitutes for the
switch statement in other languages.
• Each part must be followed with a
semicolon and whitespace is used as the
delimiters.
If-elif-else Statement
x = input("enter an integer: “)
if x < 0:
print ‘Negative’
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
Strings
• String literals consist of characters enclosed
in quotation marks (single or double)
• Use raw_input instead of input
• Individual characters are referenced by their
index (indexes start at 0)
• Negative indexes work from right to left:
>>> myName = "Joe Smith“
>>> myName[-3]
'i'
String Operations
• Slicing: selects a ‘slice’ or segment of a string
<string>[<start>:<end>]
>>> myName[2:7]
'e Smi‘
• If either <start> or <end> is omitted, the start
and end of the string are assumed
>>> myName[:5]
'Joe S'
>>> myName[4:]
'Smith'
>>> myName[:]
'Joe Smith'
String Operations
Concatenation (+)
>>> "happy" + "birthday"
'happybirthday'
>>> 'happy' + ' birthday'
'happy birthday’
Repetition (*)
>>> word = 'ha'
>>> 3 * word
'hahaha'
>>> word + 3 * '!'
'ha!!!'
String Operations
Other examples:
>>> len(word) # length function
2
>>> len("ham and eggs")
12
>>> for ch in myName:
print ch,

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>

Function call syntax:


<name>.(<actual parameters>)
>>> def square(x):
return x * x

#the blank line terminates the function


#definition
>>> square(10)
100
>>> z = 23
>>> square(z * 4)
8464
>>> square(z)
529

This function was typed in at the command line.


Later we will see how to use files and build
traditional programs.
A main program file
#File: chaos.py
#A simple program illustrating chaotic behavior

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()

You might also like