1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 8: Python’s Files, Modules, Classes and Exceptions COMP 144 Programming Language.

Slides:



Advertisements
Similar presentations
Exception Handling Genome 559. Review - classes 1) Class constructors - class myClass: def __init__(self, arg1, arg2): self.var1 = arg1 self.var2 = arg2.
Advertisements

Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
Python: Regular Expressions
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 3: Lexical Analysis COMP 144 Programming Language Concepts Spring 2002 Felix Hernandez-Campos.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 6: Introduction to Scripting Languages with Python COMP 144 Programming Language.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
Introduction to Python. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
Chapter 2 Writing Simple Programs
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 4: Syntax Specification COMP 144 Programming Language Concepts Spring 2002 Felix.
1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 7: Python’s Built-in Types and Basic Statements COMP 144 Programming Language Concepts.
The Python Programming Language Matt Campbell | Steve Losh.
Python Control of Flow.
Python, Part 2. Python Object Equality x == y x is y In Java: (x.equals(y)) (x == y)
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Python Guido van Rossum Director of PythonLabs at Zope Corporation
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Munster Programming Training
Sys.Prog & Scripting - HW Univ1 Systems Programming & Scripting Lecture 18: Regular Expressions in PHP.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Sorting and Modules. Sorting Lists have a sort method >>> L1 = ["this", "is", "a", "list", "of", "words"] >>> print L1 ['this', 'is', 'a', 'list', 'of',
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 6 Value-Returning.
H3D API Training  Part 3.1: Python – Quick overview.
RegExp. Regular Expression A regular expression is a certain way to describe a pattern of characters. Pattern-matching or keyword search. Regular expressions.
Hossain Shahriar Announcement and reminder! Tentative date for final exam need to be fixed! Topics to be covered in this lecture(s)
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
If statements while loop for loop
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Regular Expression in Java 101 COMP204 Source: Sun tutorial, …
1 Syntax Specification (Sections ) CSCI 431 Programming Languages Fall 2003 A modification of slides developed by Felix Hernandez-Campos at UNC.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Regular Expressions Regular Expressions. Regular Expressions  Regular expressions are a powerful string manipulation tool  All modern languages have.
Regular Expression What is Regex? Meta characters Pattern matching Functions in re module Usage of regex object String substitution.
Python for NLP Regular Expressions CS1573: AI Application Development, Spring 2003 (modified from Steven Bird’s notes)
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Python Functions.
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Python – reading and writing files. ??? ???two ways to open a file open and file ??? How to write to relative and absolute paths?
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
Lecture 4 Python Basics Part 3.
LECTURE 6 Advanced Functions and OOP. FUNCTIONS Before we start, let’s talk about how name resolution is done in Python: When a function executes, a new.
An Introduction to Regular Expressions Specifying a Pattern that a String must meet.
Regular expressions Day 11 LING Computational Linguistics Harry Howard Tulane University.
Regular Expressions /^Hel{2}o\s*World\n$/ SoftUni Team Technical Trainers Software University
OOP Tirgul 11. What We’ll Be Seeing Today  Regular Expressions Basics  Doing it in Java  Advanced Regular Expressions  Summary 2.
Python Joseph Eckstrom, Benjamin Moore, Willis Kornegay.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Chapter 2 Writing Simple Programs
Theory of Computation Lecture #
Strings and Serialization
Python: Experiencing IDLE, writing simple programs
Chapter 3 Lexical Analysis.
Lexical Analysis (Sections )
Introduction to Python
CS 1111 Introduction to Programming Fall 2018
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
CSCE 590 Web Scraping: Lecture 2
1.5 Regular Expressions (REs)
COMPUTER PROGRAMMING SKILLS
Lecture 7: Python’s Built-in Types and Basic Statements
CSCE 590 Web Scraping: Lecture 2
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

1 COMP 144 Programming Language Concepts Felix Hernandez-Campos Lecture 8: Python’s Files, Modules, Classes and Exceptions COMP 144 Programming Language Concepts Spring 2002 Felix Hernandez-Campos Jan 28 The University of North Carolina at Chapel Hill

2 COMP 144 Programming Language Concepts Felix Hernandez-Campos Files Creating file objectCreating file object –Syntax: file_object = open(filename, mode) »Input = open(“d:\inventory.dat”, “r”) »Output = open(“d:\report.dat”, “w”) Manual closeManual close –Syntax: close(file_object) »close(input) Reading an entire fileReading an entire file –Syntax: string = file_object.read() »content = input.read() –Syntax: list_of_strings = file_object.readlines() »lines = input.readline()

3 COMP 144 Programming Language Concepts Felix Hernandez-Campos Files Reading one line at timeReading one line at time –Syntax: list_of_strings = file_object.readline() »line = input.readline() Writing a stringWriting a string –Syntax: file_object.write(string) »output.write(“Price is %(total)d” % vars()) Writing a list of stringsWriting a list of strings –Syntax: file_object.writelines(list_of_string) »output.write(price_list) This is very simple!This is very simple! –Compare it with java.io

4 COMP 144 Programming Language Concepts Felix Hernandez-Campos Modules Long programs should be divided into different filesLong programs should be divided into different files –It makes them easier to maintain Example: mandelbrot.pyExample: mandelbrot.py # Mandelbrot module def inMandelbrotSet(point): """ True iff point is in the Mandelbrot Set """ X, t = 0 + 0j, 0 while (t < 30): if abs(X) >= 2: return 0 X, t = X ** 2 + point, t + 1 return 1

5 COMP 144 Programming Language Concepts Felix Hernandez-Campos Using Modules Importing a moduleImporting a module –Syntax: import module_name import mandelbrot p = 1+0.5j if mandelbrot.inMandelbrotSet(p): print “%f+%fj is in the set” % (p.real, p.imag) else: print “%f+%fj is NOT in the set” % (p.real, p.imag)

6 COMP 144 Programming Language Concepts Felix Hernandez-Campos Using Modules Importing functions within a modulesImporting functions within a modules –Syntax: from module_name import function_name from mandelbrot import inMandelbrotSet p = 1+0.5j if inMandelbrotSet(p): print “%f+%fj is in the set” % (p.real, p.imag) else: print “%f+%fj is NOT in the set” % (p.real, p.imag) Importing all the functions within a moduleImporting all the functions within a module –Syntax: from module_name import *

7 COMP 144 Programming Language Concepts Felix Hernandez-Campos Standard Modules Python has a very comprehensive set of standard modules (a.k.a. libraries)Python has a very comprehensive set of standard modules (a.k.a. libraries) –See Python library reference »

8 COMP 144 Programming Language Concepts Felix Hernandez-Campos string ReferenceReference – Some very useful functionsSome very useful functions –find(s, sub[, start[,end]]) –split(s[, sep[, maxsplit]]) –strip(s) –replace(str, old, new[, maxsplit])

9 COMP 144 Programming Language Concepts Felix Hernandez-Campos Regular expressions The re module provides Perl-style REsThe re module provides Perl-style REs References:References: –HOWTO » –Module reference »

10 COMP 144 Programming Language Concepts Felix Hernandez-Campos Regular Expressions A regular expression (RE) is:A regular expression (RE) is: –A single character –The empty string,  –The concatenation of two regular expressions »Notation: RE 1 RE 2 (i.e. RE 1 followed by RE 2 ) –The union of two regular expressions »Notation: RE 1 | RE 2 –The closure of a regular expression »Notation: RE* »* is known as the Kleene star »* represents the concatenation of 0 or more strings

11 COMP 144 Programming Language Concepts Felix Hernandez-Campos Defining Regular Expression Regular expression are created using compile(re)Regular expression are created using compile(re) –E.g. import re regex_object = re.compile(‘key’) Basic syntaxBasic syntax –Concatenation: sequence –Union: | –Closure: *

12 COMP 144 Programming Language Concepts Felix Hernandez-Campos Regular Expression Matching Matching at the beginning of stringsMatching at the beginning of strings –Syntax: math_object = re.match(string) –E.g. >>> import re >>> regex = re.compile('key') >>> match = regex.match("I have a key") >>> print match None >>> match = regex.match("keys open doors") >>> print match

13 COMP 144 Programming Language Concepts Felix Hernandez-Campos Regular Expression Matching Matching within stringsMatching within strings –Syntax: math_object = re.search(string) –E.g. >>> regex = re.compile('11*') >>> match = regex.match("I have $111 dollars") >>> print match None >>> match = regex.search("I have $111 dollars") >>> print match >>> match.group() '111'

14 COMP 144 Programming Language Concepts Felix Hernandez-Campos Matching Object Methods Return matched stringReturn matched string –Syntax: string = match_object.group() Return starting position of the matchReturn starting position of the match –Syntax: m = match_object.start() Return ending position of the matchReturn ending position of the match –Syntax: n = match_object.end() Return a tuple with start and end positionsReturn a tuple with start and end positions –Syntax: m, n = match_object.span()

15 COMP 144 Programming Language Concepts Felix Hernandez-Campos Extended Syntax RangesRanges –Any character within [] (e.g. [abc] ) –Any character not within [] (e.g. [^abc] ) Predefined rangesPredefined ranges –\d Matches any decimal digit; this is equivalent to the set [0-9]. –\D Matches any non-digit character; equivalent to the set [^0-9]. –\s Matches any whitespace character; this is equivalent to the set [\t\n\r\f\v]. –\S Matches any non-whitespace character; this is equivalent to the set [^ \t\n\r\f\v]. One or more closure + (e.g. a+ )One or more closure + (e.g. a+ )

16 COMP 144 Programming Language Concepts Felix Hernandez-Campos Grouping Groups are defined using parenthesesGroups are defined using parentheses –E.g. >>> regex = re.compile('(ab*)(c+)(def)') >>> match = regex.match("abbbdefhhggg") >>> print match None >>> match = regex.match("abbbcdefhhggg") >>> print match >>> match.groups() ('abbb', 'c', 'def')

17 COMP 144 Programming Language Concepts Felix Hernandez-Campos Classes Defined using class and indentationDefined using class and indentation –E.g. class MyClass: "A simple example class" "A simple example class" i = i = def f(self): def f(self): return 'hello world‘ return 'hello world‘ Methods are functions defined within the class declaration or using the dot notationMethods are functions defined within the class declaration or using the dot notation Attributes are variables defined within the the class declaration or using the dot notationAttributes are variables defined within the the class declaration or using the dot notation

18 COMP 144 Programming Language Concepts Felix Hernandez-Campos Class Constructor __init__ method__init__ method –E.g. class MyClass: def __init__(self): def __init__(self): self.data = [] self.data = [] Creation of instances is straightforwardCreation of instances is straightforward –E.g. x = MyClass()

19 COMP 144 Programming Language Concepts Felix Hernandez-Campos Class Examples ExampleExample >>> class Complex:... def __init__(self, realpart, imagpart):... self.r = realpart... self.i = imagpart... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)

20 COMP 144 Programming Language Concepts Felix Hernandez-Campos Exceptions Try/except/raiseTry/except/raise >>> while 1:... try:... x = int(raw_input("Please enter a number: "))... break... except ValueError:... print "Oops! That was not valid. Try again"...

21 COMP 144 Programming Language Concepts Felix Hernandez-Campos Reading Assignment Guido van Rossum and Fred L. Drake, Jr. (ed.), Python tutorial, PythonLabs, 2001.Guido van Rossum and Fred L. Drake, Jr. (ed.), Python tutorial, PythonLabs, –Read chapters 6 to 9 – –Write some simple programs Glance at the RE HOWTO and referenceGlance at the RE HOWTO and reference –You will need REs in the next assignment –HOWTO » –Module reference »