Docsity

Python Programming: An Introduction to EECS 448 with Dr. Douglas Niehaus - Prof. Doug Nieh, Study notes of Software Engineering

Toggle sidebar
bg1
EECS 448 Dr. Douglas Niehaus © 20091
Introduction to Python
EECS 448
Dr. Douglas Niehaus
EECS 448 Dr. Douglas Niehaus © 20092
Overview
Python is an interpreted scripting language which is
easy to use and represents a class of languages
suitable for a range of software projects
Small simple tools
One-off scripts helping with day-to-day SWE
GUI based front ends for configuration files,
command line tools, and system services
Large scale implementations have also been done
Python is comparable to
Perl, Ruby, Bash in many ways
Java in some other ways
Pyton is byte compiled and runs on a VM much as
Perl and Java
EECS 448 Dr. Douglas Niehaus © 20093
Overview
Python was explicitly designed for
Object Orientation
Extension using C/C++
C/C++ implementations of specific capabilities
are made available as Python commands
Support for Modules, which are essentially
libraries providing support for specific activities
Huge number of Python modules for a wide
range of tasks
Data base interface, multi-threading, sockets
and distributed computing, numerical
methods (NumPy), data display (Matplotlib),
graph theory, compression, image
manipulation, bioinformatics, WWW/CGI,
XML
EECS 448 Dr. Douglas Niehaus © 20094
Overview
As a scripting language, Python is dynamically typed
and can be used much more freely than a statically
typed language such as C++
Amazingly powerful code can be written in an
amazingly few lines
It can be scary and even a bit hard to figure out
why is is all working correctly
Python is has been used by Google for many years
for many of its internal implementations
Python creator Guido van Rossum employed in
part to keep developing Python
Red Hat uses Python for Kickstart Linux Setup
Django WWW framework developed at Lawrence
Journal World
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Python Programming: An Introduction to EECS 448 with Dr. Douglas Niehaus - Prof. Doug Nieh and more Study notes Software Engineering in PDF only on Docsity!

EECS 448 1 Dr. Douglas Niehaus © 2009

Introduction to Python

EECS 448

Dr. Douglas Niehaus

EECS 448 2 Dr. Douglas Niehaus © 2009

Overview

 Python is an interpreted scripting language which is

easy to use and represents a class of languages

suitable for a range of software projects

 Small simple tools

 One-off scripts helping with day-to-day SWE

 GUI based front ends for configuration files,

command line tools, and system services

 Large scale implementations have also been done

 Python is comparable to

 Perl, Ruby, Bash in many ways

 Java in some other ways

 Pyton is byte compiled and runs on a VM much as

Perl and Java

Overview

 Python was explicitly designed for

 Object Orientation

 Extension using C/C++

 C/C++ implementations of specific capabilities

are made available as Python commands

 Support for Modules, which are essentially

libraries providing support for specific activities

 Huge number of Python modules for a wide

range of tasks

 Data base interface, multi-threading, sockets

and distributed computing, numerical

methods (NumPy), data display (Matplotlib),

graph theory, compression, image

manipulation, bioinformatics, WWW/CGI,

XML

Overview

 As a scripting language, Python is dynamically typed

and can be used much more freely than a statically

typed language such as C++

 Amazingly powerful code can be written in an

amazingly few lines

 It can be scary and even a bit hard to figure out

why is is all working correctly

 Python is has been used by Google for many years

for many of its internal implementations

 Python creator Guido van Rossum employed in

part to keep developing Python

 Red Hat uses Python for Kickstart Linux Setup

 Django WWW framework developed at Lawrence

Journal World

EECS 448 5 Dr. Douglas Niehaus © 2009

Overview

 Reasonably efficient, although scripting languages

are generally somewhat slower than compiled

languages

 Psyco and other Python accelerators

 Python-to-C compilers have been tried

 Python is used for large scale high-performance

Scientific computing

 C/C++/Fortran number-crunching cores

 NumPy widely used

 Cross-Platform

 Linux/Unix, Windows, OS X

 GTK and WxWidgets cross-platform as well

EECS 448 6 Dr. Douglas Niehaus © 2009

Python Interpreter

 Python interpreter can be invoked from the command

line and some people use it as their shell

 “Bash> python” gives the Python prompt “>>>”

 Exit Python interpreter using CTL-D or

 “>>> import sys; sys.exit()”

 This imports the “sys” module and then calls

the exit() routine within the sys module name

space

 Importing a module brings in a new set of capabilities

 Elements of a module are referred to suing the

“module-name.element” naming scheme when

imported in the basic way

 Other forms available: google “Python import”

Online Resources

 Google on obvious search strings is amazingly,

although not universally effective

 www.python.org

 Home page of Python Language

 Documentation section contains links to tutorials,

module documentation and library references

 Dive into Python

 On-line book which is generally a good

introduction

 http://www.diveintopython.org/toc/index.html

Fundamentals

 Indentation and Block Structure

 Comments and Printing

 Variables and Assignment

 Expressions

 Numbers

 Strings

 Lists and Tuples

 Dictionaries

 Built-In Functions

 None Value

 Scripts

 Functions

EECS 448 13 Dr. Douglas Niehaus © 2009

Numbers

 Integers, floats, long, hex, complex

 I=5; J=12345678L; fred=0x234;

 Jane = 2.0; John = 1.567e

 Conversion routines

 Number string: print!

 string_form = print “%x” % hexnum

 String number

 Conversion routines built in for many types, including

all number types

 I = int(”345”); J=float(“23.45”); k=hex(“0x967”)

 Again – experimentation is easy, and printing the

result or type(result) almost always reveals the truth

EECS 448 14 Dr. Douglas Niehaus © 2009

Strings

 ASCII and Unicode

 Fred = “This is the ASCII string”

 John = u”This is the Unicode string”

 Unicode mostly significant for complex (more than 8-

bit) character sets

 Kanji, Arabic, Chinese, etc

 Don't worry about Unicode unless some input

requires it

 Strings are also sequence types like lists and tuples

 Wide range of methods available for operating on

strings in various ways

 strip, find, index, split, join, replace, translate

Lists and Tuples

 Very similar

 Both are sequences, as are strings

 Lists are mutable – changeable, tuples are not

 List: sequence of arbitrary elements

 [1,2,3,4,5], [“fred”, 3, 3.0,”foo”,[“list”,”within”,”list”]

 Tuples

 (1,2,3,4,5), (“fred”, 3, 3.0,”foo”)

 Slicing

 L = [1,2,3,4,5]; print L[3], L[0:3]; L[:4],L[2:]

 List Methods

 Append, count, index, insert, sort, reverse

 dir(L)

Dictionaries

 Python dictionaries a associate (key, value) pairs

 Hash tables behind the scenes

 Also serve as a front end for MySQL or other DB

 Curly braces denote a dictionary

 dict = {“key-string” : 32, 14 : “string val”}

 Key values must be “immutable”

 Integers and tuples

 Strings are among the most common

 Immutability is subtle, but changing strings

creates a new string

 Assignment

 dict[“new key] = {“a” :3, “b”: 5}

EECS 448 17 Dr. Douglas Niehaus © 2009

Dictionaries

 Useful for many purposes

 Straightforward data

collections

 C++ structure

equivalents

 Field name is the

key

 Dict of functions

 Roughly equivalent

to C++ switch

statement with each

case implemented

as a function

strct = {“FName” : “John”,

“LName” : “Smith”,

“Age” : 32}

fn_dict = {“C1” : f1, “C2” : f2,

“C3” : f3, “D” :f4}

case = classify(state, struct)

fn_dict[case](state, struct)

EECS 448 18 Dr. Douglas Niehaus © 2009

Dictionaries

 d.has_key(“LName”) checks if dictionary d has an

entry with key value “Lname”

 f.has_key(14): check if f has an entry with key 14

 key_list = d.keys() - key_list set to all keys in d

 Delete an entry: del dict[“key-value”]

 value = fred.get(13, “not-found”)

 Fetch the value associated with key 13 in fred if

present, or return string “not-found”

 Equivalent to:

if fred.has_key(13):

value = fred[13]

else:

value = “not-found”

Built-In Functions

 Some internal and introspective functions

 Compile, eval, exec: compile a string containing

python code that can be used with exec() or eval()

 dir([object]): return a directory listing of object

attribites – useful for learning about classes

defined by modules

 Math functions

 Exceptions

 Numeric Conversions

 Scan Documentation

None Special Value

 None is a special value denoting that a variable has

no content, no type, it has never been assigned into

 Can be useful when testing to see if a parameter has

been specified or ignored

EECS 448 25 Dr. Douglas Niehaus © 2009

File I/O

 Open built-in returns a file

object

 Open for read by default

 readline() method reads one

line

 readlines() reads all into one

big string variable

 read and write methods

operate on sets of characters

 dir(inf) gives a list of methods

 print can take a file object

modifier

 import sys;

sys.stdout.write(“Hello”)

inf = open(“foo.txt”)

outf = open(”fred.txt”,”w”)

line = inf.readline()

while line:

print “line:%s” % line

outf.write(line)

line = inf.readline()

inf.close()

print >>outf, “Extra Line \n”

outf.close()

EECS 448 26 Dr. Douglas Niehaus © 2009

Iteration and Looping

 range(x) creates as list of integers from 0 to x-

 range(6,x) – list from 6 through x-

 Also takes a step argument

 for loop iterates through a list of items

for i in range(7):

print “i is “, i

 Variable i assigned values 0 – 6

 Items can be any list/tuple/set, or object supporting

iteration

 for k in dict.keys():

 for char in “abcdefg”:

 for line in open(“foo.txt”)

Iteration and Looping

 While loop has obvious syntax testing condition

while a < b:

print “a is still less than b\n”

 List comprehension

 new_list = [expr(x) for x in old_list]

 expr(x) is an expression in terms of x

 x iterates through old_list, and each element of

new_list has the value expr(x) for each x in old_list

 Zip: zip(s1,s2,...,sk) take k sequences, returning a new

sequence where each element is alist of the nth

element of each of the k sequences

 Map: map(func,s) – return a new sequence whose

values are the result of func(x) for each element x in s

 Can take n sequences for n args to func

Iteration and Looping

 Reduce – reduce(func,s) can use func() to

accumulate over elements of sequence s

def sum(x,y):

return x+y

a = [1,2,3,4]

b = reduce(sum,a) # (((1+2)+3)+4)

 Filter – filter(func, s) func returns a sequence

containing elements of s for which func(s) returns

True

EECS 448 29 Dr. Douglas Niehaus © 2009

Classes

 Basic support for class definition

 Methods and variables public

 Double beginning underscore can be used for

“private” methods

 Python interpreter mangles names further

 Some standard methods begin and end with

double underscores

 Constructor - init

 Destructor - del

 All methods take “self” as a first argument

 Reference to the class instance object

EECS 448 30 Dr. Douglas Niehaus © 2009

Classes

 Constructor used to

initialize instances

 Should create all

class variables by

assigning default

values

 self.x gives access to

member variables and

methods from class

code

 Calls have “one less”

parameter than the

definition of methods

#!/usr/bin/env python

class C1:

def init(self, init_b):

self.a = 13

self.b = init_b

def m1(self):

print "M1\n"

def_ _m2(self):

return self.a

def m3(self):

return slef.b+ self.__m2()

if name == 'main':

fred = C1(36)

fred.m1()

print "result ", fred.m3()

# Uncomment for exception

# print "__m2 returns", fred._m2()

Classes

 Remember that the class statement does not create

instances of the class

 x = C() - call to constructor does that

 Inheritance works in the obvious ways

 class C(A) – defines class C as inheriting from

class A

 Operator overloading

 repr method returns a string that can be

evaluated as Python to reproduce the object

 str method returns a string used when using

a class instance as an argument of print

 add and sub are '+' and '-' operators

Modules

 Wide range of modules supporting a wide range of

functionality are available

 Brought into a Python application using any of

several forms of the “import” statement

 Any Python file can be imported as a module

 Create foo.py

 import foo

 Places where interpreter looks for foo.py is defined

by sys.path - “>>>import sys; print sys.path”

 Current directory “.” is at the frint of list

 Add elements “sys.path.append(new-dir-path)

 new-ddir-path should be an absolute path