Top Banner
Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011
45

Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Dec 29, 2015

Download

Documents

Karin Chapman
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Introduction to Python 2

Dr. Bernard ChenUniversity of Central Arkansas

PyArkansas 2011

Page 2: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

Page 3: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Files File is also one of built-in type in

Python

The built-in OPEN function creates a Python file object, which servers as a link to a file

After calling open, you can read or write the associated external file

Page 4: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Common FILE operations

INPUT

Input=open(‘file_name.txt’, ‘r’)

Input.readlines()

Input.close()

Page 5: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Split() function

>>> string= ‘a b c d e’ >>> string.split()

['a', 'b', 'c', 'd', 'e']

Page 6: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Let’s try to read in a file!!

input=open('file.txt','r')

all=[]for line in input.readlines(): temp=line.split() all.append(temp)

input.close()

Page 7: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

File in Action

Then we can calculate the average score for each student

Page 8: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

File in Action

for i in range(len(all)): sum=0.0 for j in range(1,len(all[i])): sum=sum+int(all[i][j]) average=sum/5 print average

Page 9: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

File in Action

Output

Output=open(‘file_name.txt’, ‘w’)

Output.write()

Output.close()

Page 10: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

File in Actioninput=open('file.txt','r')output=open('out_file.txt','w')

all=[]for line in input.readlines(): temp=line.split() all.append(temp)

for i in range(len(all)): sum=0.0 for j in range(1,len(all[i])): sum=sum+int(all[i][j]) average=sum/5 print average output.write(str(average)+'\n')

input.close()output.close()

Page 11: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

Page 12: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Function

In simple terms, a function is a device that groups a set of statements, so they can be run more than once in a program

Page 13: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Why Function? Functions serve two primary

development roles:1. Code Reuse: Functions allows us to

group and generalize code to be used arbitrarily many times after it is defined.

2. Procedure decomposition: Functions also provide a tool for splitting systems into pieces---one function for each subtask.

Page 14: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

“def” statement The def statement creates a function

object and assigns it to a name. the def general format:

def <name> ( ):<statements>

the statement block becomes the function’s body---the code Python executes each time the function is called

Page 15: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Function Exampledef star(): num=int(raw_input("please input a number")) for i in range(num+1): print '*' * i

star() # we call “star” function once

Page 16: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

“def” statement

Now we try to see the def format with arguments:

def <name>(arg1, arg2, …, argN):<statement>

Page 17: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Function Example with 2 argument

def multiply(x,y):value=x*yprint value

multiply(4,10)multiply(3,6)multiply(2,18)

Page 18: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Function Example with 3 argumentdef multiply(x,y,z):

value=x*y*zprint value

multiply(4,10,1) #generate result 40multiply(4,10) #error message: multiply()

takes exactly 3 arguments

(2 given)

Page 19: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

“def” statement

Now we try to see the def format with arguments and return function:

def <name>(arg1, arg2, …, argN):…return <value>

Page 20: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Function Exampledef times(x,y):

value=x*yreturn value

aa = times(2,4) #aa=8aa = times(3.14,4)#aa=12.56aa = times(“ha”,4)#aa=“hahahaha”list=[1,2,3,4]aa = times(list,2) #aa=[1,2,3,4,1,2,3,4]

Page 21: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

Page 22: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Modules

Modules are the highest level program organization unit, which packages program codes and data for reuse

Actually, each “file” is a module (Look into Lib in Python24)

Page 23: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Modules Example

>>> import random>>> random.choice(range(100))65>>> random.choice(range(100))96>>> random.choice(range(100))15

Page 24: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Why Use Modules? Modules provide an easy way to

organize components into a system, by serving as packages of names

Modules have at least three roles:1. Code Reuse2. Implementing shared services or

data3. Make everything “lives” in a Module

Page 25: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Module Creation To define a module, use your text

editor to type Python code into a text file

You may create some functions or variables in that file

You can call modules anything, but module filenames should end in .py suffix

Page 26: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Modules Usage

Clients can use the module file we just wrote by running “import” statement

>>> import math>>> import random>>> import module1 # assume this is

the file name we saved

Page 27: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Modules examples

We create a file name module1:

def print_out(aa):print aa*3

Page 28: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Modules Example now we write another file named module2

import module1

module1.print_out(“Hello World!! ”) # Use module1’s function

The result of execute this program is: Hello World!! Hello World!! Hello World!!

Page 29: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Modules

You may also use variables in a Module For example:

>>> import math>>> math.pi3.1415926535897931

Page 30: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

Page 31: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

What is OOP

To qualify as being truly object-oriented objects generally need to also participate in something called an inheritance hierarchy

Inheritance --- a mechanism of code customization and reuse, above and beyond anything we’ve seen so far

Page 32: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class tree Two key words need to define:

1. ClassesServe as instance factory

2. InstancesRepresent the product generate from classes

Page 33: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class tree

Page 34: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class tree

We usually call class higher in the tree (like c2 and c3) superclasses; classes lower in the tree (like c1) are known as subclasses

The search procedure (try to look up some specific function belongs to which class) proceeds bottom-up, starting from left to right

Page 35: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class tree Suppose we build up the tree If we say: I2.w It indicates we have an instance2 and it calls

the function w now, we need to search where does the

function w defined Therefore, the Python will search the linked

objects in the order: I2, C1, C2, C3 and stop at the first .w it finds In OOP, I2 “inherits” w from C3

Page 36: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class tree I1.x and I2.x both find x in C1 and

stop, since C1 is lower than C2 I1.y and I2.y both find y in C1,

since that’s the only y I1.z and I2.z both find z in C2,

since C2 is more to the left than C3 I2.name finds name in I2, without

climbing the tree at all

Page 37: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class vs. Modules All of the class and instance

objects we put in these trees are just package of names.

If that sounds like modules, it should;

The only difference here is that objects in class tree also have “automatically-search” links to other namespace objects.

Page 38: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Coding the Class Tree

Each “class” statement generates a new class object

Each time a class is called, it generates a new “instance” object

Instances are automatically linked to the class they are created from

Classes are linked to their superclasses

Page 39: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Coding the Class Tree To build the class tree we just saw, we

would run Python code in this form:

class C2: …class C3: …class C1 (C2,C3): …

I1=C1()I2=C2()

Page 40: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

A First Example

Page 41: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class Tree

Page 42: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

A Second Example

Page 43: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

A Second Example

Page 44: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Class Tree

Page 45: Introduction to Python 2 Dr. Bernard Chen University of Central Arkansas PyArkansas 2011.

Python Official Sites

Python Tutorial http://docs.python.org/tut/

Python Official Site http://python.org/

Download Python Latest Version http://python.org/download/