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

Post on 29-Dec-2015

216 views 0 download

Tags:

Transcript of 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

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

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

Common FILE operations

INPUT

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

Input.readlines()

Input.close()

Split() function

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

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

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

File in Action

Then we can calculate the average score for each student

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

File in Action

Output

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

Output.write()

Output.close()

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

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

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

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.

“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

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

“def” statement

Now we try to see the def format with arguments:

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

Function Example with 2 argument

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

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

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)

“def” statement

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

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

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]

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

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)

Modules Example

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

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

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

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

Modules examples

We create a file name module1:

def print_out(aa):print aa*3

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!!

Modules

You may also use variables in a Module For example:

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

Outline

File I/O Function Modules Object Oriented Programming

(OOP)

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

Class tree Two key words need to define:

1. ClassesServe as instance factory

2. InstancesRepresent the product generate from classes

Class tree

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

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

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

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.

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

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

A First Example

Class Tree

A Second Example

A Second Example

Class Tree

Python Official Sites

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

Python Official Site http://python.org/

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