Xi Wang Yang Zhang. 1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Dictionaries: Keeping track of pairs
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Introduction to Computing Using Python Text Data, File I/O, and Exceptions  Strings, revisited  Formatted output  File Input/Output  Errors and Exceptions.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
DICTIONARIES. The Compound Sequence Data Types All of the compound data types we have studies in detail so far – strings – lists – Tuples They are sequence.
Topics This week: File input and output Python Programming, 2/e 1.
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
© Copyright 2012 by Pearson Education, Inc. All Rights Reserved. Chapter 13 Files and Exception Handling 1.
CS 177 Week 11 Recitation Slides 1 1 Dictionaries, Tuples.
October 4, 2005ICP: Chapter 4: For Loops, Strings, and Tuples 1 Introduction to Computer Programming Chapter 4: For Loops, Strings, and Tuples Michael.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Python for Informatics: Exploring Information
Python Programming Chapter 7: Strings Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Strings CSE 1310 – Introduction to Computers and Programming Vassilis Athitsos University of Texas at Arlington 1.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s)
Programming in Python Part III Dr. Fatma Cemile Serçe Atılım University
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
Built-in Data Structures in Python An Introduction.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 8 Working.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Python – reading and writing files. ??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?
JSON COMPSCI 105 SS 2015 Principles of Computer Science.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
FILES. open() The open() function takes a filename and path as input and returns a file object. file object = open(file_name [, access_mode][, buffering])
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
COSC 1306—COMPUTER SCIENCE AND PROGRAMMING PYTHON TUPLES, SETS AND DICTIONARIES Jehan-François Pâris
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
Python Files and Lists. Files  Chapter 9 actually introduces you to opening up files for reading  Chapter 14 has more on file I/O  Python can read.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
Strings CSE 1310 – Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington 1.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
Control Statements 1. Conditionals 2 Loops 3 4 Simple Loop Examples def echo(): while echo1(): pass def echo1(): line = input('Say something: ') print('You.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
CSc 120 Introduction to Computer Programing II Adapted from slides by
Catapult Python Programming Wednesday Morning session
CSc 120 Introduction to Computer Programing II Adapted from slides by
Chapter 8 Text Files We have, up to now, been storing data only in the variables and data structures of programs. However, such data is not available.
Module 4 String and list – String traversal and comparison with examples, List operation with example, Tuples and Dictionaries-Operations and examples.
Catapult Python Programming Thursday Session
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
CSc 120 Introduction to Computer Programing II
Tutorial Lecture for EE562 Artificial Intelligence for Engineers
And now for something completely different . . .
Internet-of-Things (IoT)
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Python’s Errors and Exceptions
File IO and Strings CIS 40 – Introduction to Programming in Python
Using files Taken from notes by Dr. Neil Moore
(Oops! When things go wrong)
COSC 1306 COMPUTER SCIENCE AND PROGRAMMING
Python Lists and Sequences
CS1110 Today: collections.
By Ryan Christen Errors and Exceptions.
“Everything Else”.
Topics Introduction to File Input and Output
Presentation transcript:

Xi Wang Yang Zhang

1. Strings 2. Text Files 3. Exceptions 4. Classes  Refer to basics 2.py for the example codes for this section.

 Strings are made up of characters.  Slice a string >>> fruit = 'apple' >>> fruit[1] 'p' >>> fruit[0] 'a' apple index

>>> fruit[-1] 'e' >>> fruit[0:2] 'ap' >>> fruit[2:] 'ple' >>> len(fruit) 5

 Strings are immutable: >>> fruit[0] = "A" Traceback (most recent call last): File " ", line 1, in TypeError: 'str' object does not support item assignment

 Use for loop to process a string: >>> for char in fruit: print char a p p l e

>>> prefixes = "JKL" >>> suffix = "ack" >>> for letter in prefixes: print letter + suffix Jack Kack Lack

 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

>>> def removeP(s): newString = ' ' for letter in s: if letter != 'p': newString += letter return newString >>> removeP(fruit) 'ale'

 String methods are functions for strings. >>> greeting = "Good morning!" >>> greeting.upper() GOOD MORNING! >>> greeting.lower() good morning!

>>> badGreeting = " GOOd mOrning! " >>> badGreeting.strip() 'GOOd mOrning!' >>> badGreeting.replace(“O",“o") ' Good morning! ' >>> badGreeting.split() ['GOOd', 'mOrning!']

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

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

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

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

>>> print file.read(5) # Line >>> print file.readline() one >>> print file.readline() # Line two

>>> print file.readlines() ['# Line three \n', 'Now is the time to close the file. \n'] >>> file.close()

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

>>> filter("test.txt", "newfile.txt") >>> newfile = open("newfile.txt") >>> print newfile.read() Now is the time to close the file.

1. Tuples 2. Lists 3. Dictionaries  They are used to store data.

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

 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

 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

 Lists are just like tuples except that lists are mutable: >>> myList = ['apple', 3, True] >>> myList[-1] = False >>> myList ['apple', 3, False]

 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]

 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

 Useful list methods: >>> socialScience = ['sociology', 'chemistry'] >>> socialScience.append('political science') >>> socialScience ['sociology', 'chemistry', 'political science'] >>> socialScience.remove('chemistry') >>> socialScience ['sociology', 'political science']

>>> socialScience.insert(1, 'economics') >>> socialScience ['sociology', 'economics', 'political science'] >>> socialScience.count('political science') 1 >>> socialScience.index('political science') 2

 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}

 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}

 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}

 Whenever a runtime error occurs, it creates and exception, and the program stops.

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

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

def open_file(filename): try: f = open(filename, "r") print filename, 'now is open.' except: print 'There is no file named', filename

>>> open_file('test.txt') test.txt now is open. >>> open_file('test.dat') There is no file named test.dat

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

 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

>>> p = Point(3,4) >>> p.x 3 >>> p.y 4 >>> p.distanceFromOrigin() 5.0

class Student(object): counter = 0 def __init__(self): Student.counter += 1 self.id = Student.counter def getType(self): return 'Student'

class Undergrad(Student): def __init__(self, year): Student.__init__(self) self.year = year def getType(self): return 'Undergraduate Student'

>>> student1 = Student() >>> student1.id 1 >>> student2 = Student() >>> student2.id 2 >>> student3 = Undergrad(2015) >>> student3.id 3

>>> student1.year AttributeError: 'Student' object has no attribute 'year' >>> student3.year 2015 >>> student1.getType() ‘Student’ >>> student3.getType() ‘Undergraduate Student’