Download presentation
Presentation is loading. Please wait.
Published byBrook Dinah Johns Modified over 8 years ago
1
Xi Wang Yang Zhang
2
1. Strings 2. Text Files 3. Exceptions 4. Classes Refer to basics 2.py for the example codes for this section.
3
Strings are made up of characters. Slice a string >>> fruit = 'apple' >>> fruit[1] 'p' >>> fruit[0] 'a' apple 01234 index
4
>>> fruit[-1] 'e' >>> fruit[0:2] 'ap' >>> fruit[2:] 'ple' >>> len(fruit) 5
5
Strings are immutable: >>> fruit[0] = "A" Traceback (most recent call last): File " ", line 1, in TypeError: 'str' object does not support item assignment
6
Use for loop to process a string: >>> for char in fruit: print char a p p l e
7
>>> prefixes = "JKL" >>> suffix = "ack" >>> for letter in prefixes: print letter + suffix Jack Kack Lack
8
The in operation tests if one string is a substring of another: >>> 'a' in fruit True >>> 'o' in fruit False >>> 'o' not in fruit True >>> 'pp' in fruit True
9
>>> def removeP(s): newString = ' ' for letter in s: if letter != 'p': newString += letter return newString >>> removeP(fruit) 'ale'
10
String methods are functions for strings. >>> greeting = "Good morning!" >>> greeting.upper() GOOD MORNING! >>> greeting.lower() good morning!
11
>>> badGreeting = " GOOd mOrning! " >>> badGreeting.strip() 'GOOd mOrning!' >>> badGreeting.replace(“O",“o") ' Good morning! ' >>> badGreeting.split() ['GOOd', 'mOrning!']
12
When a program is running, its data is stored in random access memory (RAM). If you want to use the data after ending the program, you need to write the data to a file in a non-volatile storage medium (such as hard drive and flash drive).
13
A text file is a file that contains printable characters and whitespace, organized into lines separated by newline characters (\n). Working with a text file is like working with a notebook.
14
>>> file = open('test.txt', 'w') >>> print file >>> file.write("# Line one \n") >>> file.write("# Line two \n") >>> file.write("# Line three \n") >>> file.write("Now is the time to close the file. \n") >>> file.close()
15
>>> file = open('test.txt', 'r') >>> file = open('test.dat', 'r') IOError: [Errno 2] No such file or directory: 'test.dat' >>> text = file.read() >>> print text Line one Line two Line three Now is the time to close the fille.
16
>>> print file.read(5) # Line >>> print file.readline() one >>> print file.readline() # Line two
17
>>> print file.readlines() ['# Line three \n', 'Now is the time to close the file. \n'] >>> file.close()
18
def filter(oldfile, newfile): infile = open(oldfile, 'r') outfile = open(newfile, 'w') while True: text = infile.readline() if text == "": break if text[0] == '#': continue outfile.write(text) infile.close() outfile.close() return
19
>>> filter("test.txt", "newfile.txt") >>> newfile = open("newfile.txt") >>> print newfile.read() Now is the time to close the file.
20
1. Tuples 2. Lists 3. Dictionaries They are used to store data.
21
Tuples can be made up of anything. >>> myTuple = ('apple', 3, True) Tuples and strings are indexed in a similar way. >>> myTuple[0] 'apple' >>> myTuple[-1] True >>> myTuple[0:2] ('apple', 3)
22
Like strings, tuples are immutable. >>> myTuple[-1] = False Traceback (most recent call last): File " ", line 1, in TypeError: ‘tuple' object does not support item assignment
23
Iteration over a tuple: >>> fruitTuple = ('apples', 'bananas', 'oranges') >>> for fruit in fruitTuple: print 'I love', fruit I love apples I love bananas I love oranges
24
Lists are just like tuples except that lists are mutable: >>> myList = ['apple', 3, True] >>> myList[-1] = False >>> myList ['apple', 3, False]
25
Side effect of mutability >>> numList1 = [10, 20, 30, 40] >>> numList2 = numList1 >>> numList3 = numList1[:] >>> numList1[0] = 0 >>> numList1 [0, 20, 30, 40] >>> numList2 [0, 20, 30, 40] >>> numList3 [10, 20, 30, 40]
26
Functions and operators for lists: >>> range(1,5) [1, 2, 3, 4] >>> range(5) [0, 1, 2, 3, 4] >>> len(myList) 3 >>> False in myList True
27
Useful list methods: >>> socialScience = ['sociology', 'chemistry'] >>> socialScience.append('political science') >>> socialScience ['sociology', 'chemistry', 'political science'] >>> socialScience.remove('chemistry') >>> socialScience ['sociology', 'political science']
28
>>> socialScience.insert(1, 'economics') >>> socialScience ['sociology', 'economics', 'political science'] >>> socialScience.count('political science') 1 >>> socialScience.index('political science') 2
29
Strings, tuples, and lists use integers as indices. Dictionaries map keys to values. Create a dictionary >>> months = {} >>> months['Jan'] = 1 >>> months['Feb'] = 2 >>> months['Mar'] = 3 >>> months {'Feb': 2, 'Jan': 1, 'Mar': 3}
30
Dictionary operators and functions >>> 'Jan' in months True >>> ‘Apr‘ not in months True >>> months['Feb'] 2 >>> len(months) 3 >>> months['Jan'] = 0 >>> months {'Feb': 2, 'Jan': 0, 'Mar': 3}
31
Dictionary methods >>> months.items() [('Jan', 0), ('Mar', 3), ('Feb', 2)] >>> months.keys() ['Jan', 'Mar', 'Feb'] >>> months.values() [0, 3, 2] >>> months.pop('Jan') 0 >>> months {'Feb': 2, 'Mar': 3}
32
Whenever a runtime error occurs, it creates and exception, and the program stops.
33
>>> 3/0 ZeroDivisionError: integer division or modulo by zero >>> tup = (1,2,3) >>> print tup[3] IndexError: tuple index out of range tup[0] = 0 TypeError: 'tuple' object does not support item assignment
34
>>> int(tup) TypeError: int() argument must be a string or a number, not 'tuple' >>> print mytup NameError: name 'mytup' is not defined >>> file = open('test.dat', 'r') IOError: [Errno 2] No such file or directory: 'test.dat'
35
def open_file(filename): try: f = open(filename, "r") print filename, 'now is open.' except: print 'There is no file named', filename
36
>>> open_file('test.txt') test.txt now is open. >>> open_file('test.dat') There is no file named test.dat
37
Python is an object-oriented programming language. Up to now we have been using procedural programming which focuses on writing functions that operate on data. In object-oriented programming, the focus is on creating objects that contain both data and functions.
38
A class defines a new data type. Let’s define a new class called Point. >>> class Point: def __init__(self, x, y): self.x = x self.y = y def distanceFromOrigin(self): return (self.x**2 + self.y**2)**0.5
39
>>> p = Point(3,4) >>> p.x 3 >>> p.y 4 >>> p.distanceFromOrigin() 5.0
40
class Student(object): counter = 0 def __init__(self): Student.counter += 1 self.id = Student.counter def getType(self): return 'Student'
41
class Undergrad(Student): def __init__(self, year): Student.__init__(self) self.year = year def getType(self): return 'Undergraduate Student'
42
>>> student1 = Student() >>> student1.id 1 >>> student2 = Student() >>> student2.id 2 >>> student3 = Undergrad(2015) >>> student3.id 3
43
>>> student1.year AttributeError: 'Student' object has no attribute 'year' >>> student3.year 2015 >>> student1.getType() ‘Student’ >>> student3.getType() ‘Undergraduate Student’
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.