ch 12d_python fundamentals
TRANSCRIPT
-
8/8/2019 Ch 12d_Python Fundamentals
1/63
Python Fundamentals
Scripting Languages
-
8/8/2019 Ch 12d_Python Fundamentals
2/63
References
http://www.linuxjournal.com/article/3882 Why Python? by EricRaymond 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, IEEEComputer, March 1998.
http://www.geeksaresexy.net/2008/07/25/the-ascent-of-scripting-languages/ 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/
-
8/8/2019 Ch 12d_Python Fundamentals
3/63
What is a Scripting Language?
Wikipedia: A scripting language, script
language orextension language, is a
programming language that controls asoftware application. "Scripts" are often
treated as distinct from programs", which
execute independently from any other
application.
-
8/8/2019 Ch 12d_Python Fundamentals
4/63
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.
-
8/8/2019 Ch 12d_Python Fundamentals
5/63
Example Shell Script
from Ousterhout select | grep scripting | wc
where
selectis 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";
wcis a program to count the lines in its input.
| is the pipe command that directs the outputfrom one program to the input of the nextprogram.
-
8/8/2019 Ch 12d_Python Fundamentals
6/63
Modern Scripting Languages
Perl, Python, Ruby,
More like a traditional programming
language than early scripting languages. Higher level in the sense that programmers
dont have to worry about many of the
details that are a part of C-like languages
No explicit memory allocation/deallocation, for
example
-
8/8/2019 Ch 12d_Python Fundamentals
7/63
Modern Scripting Languages
Its possible to write full-featured programs
in these languages
Used frequently today for quick-and-dirtyprogramming
Quick results
Small programs
See next definition
-
8/8/2019 Ch 12d_Python Fundamentals
8/63
What is a Scripting Language?
"scripting language." Encyclopdia Britannica. 2008.Encyclopdia Britannica Online. 30 Sep. 2008.
Scripting languages are sometimes called littlelanguages. They are intended to solve relatively smallprogramming problems that do not require the overheadof data declarations and other features needed to makelarge programs manageable. Scripting languages are
used for writing operating system utilities, for special-purpose file-manipulation programs, and, because theyare easy to learn.
-
8/8/2019 Ch 12d_Python Fundamentals
9/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
10/63
Why Python?
No universal agreement on which scriptinglanguage is best
Perl, Ruby, others also have advocates
Perl: good for system administrationduties, traditional scripting
Awkward syntax, OO as an afterthought, less
readable than other languages Python has attracted many former Perl
users
-
8/8/2019 Ch 12d_Python Fundamentals
11/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
12/63
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 willcause older programs to break.
Part of the Python philosophy dont clutter up thelanguage with outdated features
Write your programs to run in the CS lab (v 3.1).
-
8/8/2019 Ch 12d_Python Fundamentals
13/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
14/63
Execution Modes
Calculator mode: type in an expression,Python will evaluate it:
>>> a = 5>>> b = 10
>>> a+b15
Dynamic change of type>>> a = 'horse>>> a = cart>>> a + b
horse cart
-
8/8/2019 Ch 12d_Python Fundamentals
15/63
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 thefactorial o
f, n, is,
fact
main( )
-
8/8/2019 Ch 12d_Python Fundamentals
16/63
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
Cant be used in an expression unless it has a value
Error message: Name Error means no value is
associated with this name
-
8/8/2019 Ch 12d_Python Fundamentals
17/63
Variables
Variable names dont have types values
(or objects) do
A variable name has the type of the value itcurrently references
Variables actually contain references to
values (similar to pointers).
This makes it possible to assign different
object types to the same variable
-
8/8/2019 Ch 12d_Python Fundamentals
18/63
A 3.5A 3.5
7.0
A = A * 2
A = cat
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 anyinaccessible memory locations.
Python does not implement reference semantics; if A = 10 and
B = A, A = A + 1 does not change the value of B
Variables contain references to data values
-
8/8/2019 Ch 12d_Python Fundamentals
19/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
20/63
Output Statements
Statement syntax: (EBNF notation)print {expression,}
where the final comma in the list is optional
Examples:print # prints a blank lineprint 3, y, z + 10 # go to new lineprint the result is z,# no new line
Output items are automatically separated by asingle space.
-
8/8/2019 Ch 12d_Python Fundamentals
21/63
Assignment Statements
Syntax: Assignment variable = expression A variables 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
>>>
-
8/8/2019 Ch 12d_Python Fundamentals
22/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
23/63
Input
The input statement can be part of a multipleassignment statement:
>>> x, y = input("enter two comma-separated
values: ")
enter two comma-separated values: 13, 26
>>> x
13
>>> y
26
-
8/8/2019 Ch 12d_Python Fundamentals
24/63
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!'
>>>
-
8/8/2019 Ch 12d_Python Fundamentals
25/63
Raw_input versus input
raw_inputreads everything as a string
Using raw_inputis a safety measure for
reading data use a cast to get correcttype, if necessaryr = float(raw_input(enter radius))
Now, if user enters something inappropriate,Python will throw an exception.
-
8/8/2019 Ch 12d_Python Fundamentals
26/63
Python Control Structures
Python loop types:
while
for
Decision statements: if
Related features:
range( )#
af
unction break # statements similar to
continue # those in C/C++
-
8/8/2019 Ch 12d_Python Fundamentals
27/63
General Information
The first statement in the body of a loop
must be indented.
All other statements must be indented bythe same amount
To terminate a loop body, enter a blank
line.
-
8/8/2019 Ch 12d_Python Fundamentals
28/63
While Loop
>>> x = 0>>> while (x < 10): #remember semicolon!
print x, #prints on one linex = 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 trueThe conditional operators are also the same
Note indentation provided by the IDLE GUI
-
8/8/2019 Ch 12d_Python Fundamentals
29/63
For Loops
Syntax:
for in :
can be a list of values or itcan 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
-
8/8/2019 Ch 12d_Python Fundamentals
30/63
>>> 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
68
10
-
8/8/2019 Ch 12d_Python Fundamentals
31/63
Ranges can also be specified usingexpressions:
>>> n = 5
>>> for i in range(2*n +3):print i,
0 1 2 3 4 5 6 7 8 9 10 11 12
-
8/8/2019 Ch 12d_Python Fundamentals
32/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
33/63
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 theswitch statement in other languages.
Each part must be followed with asemicolon and whitespace is used as thedelimiters.
-
8/8/2019 Ch 12d_Python Fundamentals
34/63
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'
-
8/8/2019 Ch 12d_Python Fundamentals
35/63
Strings
String literals consist of characters enclosedin quotation marks (single or double)
Use raw_input instead ofinput
Individual characters are referenced by theirindex (indexes start at 0)
Negative indexes work from right to left:
>>> myName = "Joe Smith>>> myName[-3]
'i'
-
8/8/2019 Ch 12d_Python Fundamentals
36/63
String Operations
Slicing: selects a slice or segment of a string[:]>>> myName[2:7]'e Smi
If eitheroris omitted, the startand end of the string are assumed>>> myName[:5]
'Joe S'
>>> myName[4:]'Smith'
>>> myName[:]
'Joe Smith'
-
8/8/2019 Ch 12d_Python Fundamentals
37/63
String Operations
Concatenation (+)>>> "happy" + "birthday"
'happybirthday'
>>> 'happy' + ' birthday'
'happy birthday
Repetition (*)>>> word = 'ha'
>>> 3 * word
'hahaha'
>>> word + 3 * '!'
'ha!!!'
-
8/8/2019 Ch 12d_Python Fundamentals
38/63
String Operations
Other examples:>>> len(word) # length function2
>>> len("ham and eggs")12>>> for ch in myName:
print ch,
J o e S m i t h
-
8/8/2019 Ch 12d_Python Fundamentals
39/63
Lists
A list is a comma-separated sequence of
items, enclosed in square brackets
Lists can be heterogeneous items donthave 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
-
8/8/2019 Ch 12d_Python Fundamentals
40/63
>>> 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']
-
8/8/2019 Ch 12d_Python Fundamentals
41/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
42/63
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]
-
8/8/2019 Ch 12d_Python Fundamentals
43/63
Sequences
Strings and lists are both sequences.
Sequence operations include
+ concatenation * (int-exp> repetition
[ ] indexing
[ : ] slicing
len() length
for in iteration
-
8/8/2019 Ch 12d_Python Fundamentals
44/63
Nested Lists
>>> grades = [100, 97, 85]
>>> stRec = ['A000','jack',grades]
>>> stRec['A000', 'jack', [100, 97, 85]]
>>> len(stRec)
3
-
8/8/2019 Ch 12d_Python Fundamentals
45/63
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
-
8/8/2019 Ch 12d_Python Fundamentals
46/63
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']
-
8/8/2019 Ch 12d_Python Fundamentals
47/63
Dictionaries
Also called associative arrays
Resemble hash tables
Unlike sequences (lists, strings) which areindexed 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
-
8/8/2019 Ch 12d_Python Fundamentals
48/63
>>> 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
>>>
-
8/8/2019 Ch 12d_Python Fundamentals
49/63
Python Functions
A Python function can be either void orvalue returning, although the definition isntidentified as such.
Technically, they are all value returning, sincea void function returns the value none
Each function defines a scope. Parametersand local variables are accessible in thescope; values in other functions areavailable only as parameters.
-
8/8/2019 Ch 12d_Python Fundamentals
50/63
Function Syntax
Function definition
def (formal-parameters>):
Function call syntax:
.()
-
8/8/2019 Ch 12d_Python Fundamentals
51/63
>>> 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.
-
8/8/2019 Ch 12d_Python Fundamentals
52/63
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()
-
8/8/2019 Ch 12d_Python Fundamentals
53/63
Functions That Return Values
>>> def sum(x, y):
sum = x + y
return sum
>>> num1,num2 = 3,79
>>> sum(num1, num2)
82
>>> def SumDif(x,y):
sum = x + y
dif = x - y
return sum, dif
>>> a,b = SumDif(x,y)
>>> a
17
>>> print a, b
17 -3
>>>
-
8/8/2019 Ch 12d_Python Fundamentals
54/63
Parameters
Parameters are passed by value, so ingeneral the actual parameters cant bechanged 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 ofpointers, and these pointers remain the same;only the things pointed to change!
(dont worry about the subtleties here)
-
8/8/2019 Ch 12d_Python Fundamentals
55/63
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 cant be changed in place;
list items can be.
-
8/8/2019 Ch 12d_Python Fundamentals
56/63
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]
-
8/8/2019 Ch 12d_Python Fundamentals
57/63
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']
-
8/8/2019 Ch 12d_Python Fundamentals
58/63
Strings Continued
When using string functions begin byimporting the string library: import string
After you have split a string into a list ofsubstrings, you may want to convert someof the substrings to specific data types. Thegeneric function is eval() and thereare specific casts: int( ), float( ), long( ), andstr( ).
-
8/8/2019 Ch 12d_Python Fundamentals
59/63
Example
>>> x = myStr.split('/')
>>> x
['12', '10', '2008']
>>> print eval(x[0]),int(x[1]),float(x[2])
12 10 2008.0
-
8/8/2019 Ch 12d_Python Fundamentals
60/63
File I/O
= open(, )
where name is the name of the file on disk, andmode is either r or w
infile = open(data.in, r)
outfile = open(data.out, w)
Files must also be closed:
infile.close( )
outfile.close( )
-
8/8/2019 Ch 12d_Python Fundamentals
61/63
Input Operations
.read: returns the remaining
contents of the file as a multi-line string (lines in
the file separated by \n)
.readline( ): returns next lineas a string; includes the newline character (you
can slice it off, if needed)
.readlines( ): returns the
remaining lines in the file, as a list of lines (eachlist item includes the newline character)
-
8/8/2019 Ch 12d_Python Fundamentals
62/63
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
% ()
Possible formats are d (decimal), f (float)
and s (string)
-
8/8/2019 Ch 12d_Python Fundamentals
63/63
Example
>>> outfile=open("C:\Temp\exmp.out","w")
>>> outfile.write("this is the first
line\n")>>> outfile.write('and this is thesecond\n')
>>> outfile.write("the value of x is%d and y is %f" % (x, y))
>>> outfile.close()