1 / 45

Introduction to Python 2

Introduction to Python 2. Dr. Bernard Chen University 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

Download Presentation

Introduction to Python 2

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. Outline • File I/O • Function • Modules • Object Oriented Programming (OOP)

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

  4. Common FILE operations • INPUT • Input=open(‘file_name.txt’, ‘r’) • Input.readlines() • Input.close()

  5. Split() function • >>> string= ‘a b c d e’ • >>> string.split() ['a', 'b', 'c', 'd', 'e']

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

  7. File in Action • Then we can calculate the average score for each student

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

  9. File in Action • Output • Output=open(‘file_name.txt’, ‘w’) • Output.write() • Output.close()

  10. File in Action input=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()

  11. Outline • File I/O • Function • Modules • Object Oriented Programming (OOP)

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

  13. Why Function? • Functions serve two primary development roles: • Code Reuse: Functions allows us to group and generalize code to be used arbitrarily many times after it is defined. • Procedure decomposition: Functions also provide a tool for splitting systems into pieces---one function for each subtask.

  14. “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

  15. Function Example def star(): num=int(raw_input("please input a number")) for i in range(num+1): print '*' * i star() # we call “star” function once

  16. “def” statement • Now we try to see the def format with arguments: def <name>(arg1, arg2, …, argN): <statement>

  17. Function Example with 2 argument def multiply(x,y): value=x*y print value multiply(4,10) multiply(3,6) multiply(2,18)

  18. Function Example with 3 argument def multiply(x,y,z): value=x*y*z print value multiply(4,10,1) #generate result 40 multiply(4,10) #error message: multiply() takes exactly 3 arguments (2 given)

  19. “def” statement • Now we try to see the def format with arguments and return function: def <name>(arg1, arg2, …, argN): … return <value>

  20. Function Example def times(x,y): value=x*y return value aa = times(2,4) #aa=8 aa = times(3.14,4)#aa=12.56 aa = times(“ha”,4)#aa=“hahahaha” list=[1,2,3,4] aa = times(list,2) #aa=[1,2,3,4,1,2,3,4]

  21. Outline • File I/O • Function • Modules • Object Oriented Programming (OOP)

  22. 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)

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

  24. 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: • Code Reuse • Implementing shared services or data • Make everything “lives” in a Module

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

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

  27. Modules examples • We create a file name module1: def print_out(aa): print aa*3

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

  29. Modules • You may also use variables in a Module • For example: >>> import math >>> math.pi 3.1415926535897931

  30. Outline • File I/O • Function • Modules • Object Oriented Programming (OOP)

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

  32. Class tree • Two key words need to define: 1. Classes Serve as instance factory 2. Instances Represent the product generate from classes

  33. Class tree

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

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

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

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

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

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

  40. A First Example

  41. Class Tree

  42. A Second Example

  43. A Second Example

  44. Class Tree

  45. Python Official Sites Python Tutorial • http://docs.python.org/tut/ Python Official Site • http://python.org/ Download Python Latest Version • http://python.org/download/

More Related