LECTURE 4 Python Basics Part 3

Similar documents
FILE HANDLING AND EXCEPTIONS

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

CIS192 Python Programming

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

Python Tutorial. Day 2

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Exceptions CS GMU

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

CS Programming Languages: Python

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

STSCI Python Introduction. Class URL

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Introduction to python

Exceptions and File I/O

F21SC Industrial Programming: Python: Classes and Exceptions

Algorithms and Programming

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file:

Python File Modes. Mode Description. Open a file for reading. (default)

LECTURE 9 The Standard Library Part 3

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Exceptions & a Taste of Declarative Programming in SQL

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

CSC148 Fall 2017 Ramp Up Session Reference

LECTURE 7. The Standard Library Part 1: Built-ins, time, sys, and os

Exception Handling. Genome 559

#11: File manipulation Reading: Chapter 7

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Files on disk are organized hierarchically in directories (folders). We will first review some basics about working with them.

Introduction to Python! Lecture 2

Lecture #12: Quick: Exceptions and SQL

CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Lecture 21. Programming with Subclasses

Abstract Data Types Chapter 1

Class extension and. Exception handling. Genome 559

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

A Little Python Part 3

Class extension and. Exception handling. Genome 559

381 INTRODUCTION TO PYTHON SUSHIL J. LOUIS

Lecture 21. Programming with Subclasses

COMP 204: Sets, Commenting & Exceptions

Computational Methods of Scientific Programming. Lecturers Thomas A Herring Chris Hill

CS 11 python track: lecture 2

Lecture 18. Classes and Types

Modules and scoping rules

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Programming in Python 3

MEIN 50010: Python Strings

Reading and writing files

A Little Python Part 3

Exception Handling and Debugging

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Script language: Python Data and files

CS116 - Module 10 - File Input/Output

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

Lecture 21. Programming with Subclasses

Guide to Programming with Python. Algorithms & Computer programs. Hello World

Final Exam Version A

Python for Non-programmers

The current topic: Python. Announcements. Python. Python

CS 115 Lecture 4. More Python; testing software. Neil Moore

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Python for Non-programmers

4.3 FURTHER PROGRAMMING

Mode Meaning r Opens the file for reading. If the file doesn't exist, fopen() returns NULL.

Part III Appendices 165

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Exceptions & error handling in Python 2 and Python 3

Review 3. Exceptions and Try-Except Blocks

COMP 204: Sets, Commenting & Exceptions

CSc 110, Spring Lecture 24: print revisited, tuples cont.

Idioms and Anti-Idioms in Python

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

Single Source Python 2 3

Introduction to programming using Python

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

STSCI Python Introduction

1 Strings (Review) CS151: Problem Solving and Programming

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I

Introduction to: Computers & Programming: Exception Handling

Slide Set 15 (Complete)

CS Lecture 26: Grab Bag. Announcements

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

MEIN 50010: Python Flow Control

Advanced Python. Executive Summary, Session 1

Ch.4: User input and error handling

Here n is a variable name. The value of that variable is 176.

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

Lecture 8. Introduction to Python! Lecture 8

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Control Structures 1 / 17

Transcription:

LECTURE 4 Python Basics Part 3

INPUT We ve already seen two useful functions for grabbing input from a user: raw_input() Asks the user for a string of input, and returns the string. If you provide an argument, it will be used as a prompt. input() Uses raw_input() to grab a string of data, but then tries to evaluate the string as if it were a Python expression. Returns the value of the expression. Dangerous don t use it. Note: In Python 3.x, input() is now just raw_input(). >>> print(raw_input('what is your name? ')) What is your name? Caitlin Caitlin >>> >>> print(input(do some math: )) Do some math: 2+2*5 12 >>> Note: reading an EOF will raise an EOFError.

FILES Python includes a file object that we can use to manipulate files. There are two ways to create file objects. Use the file() constructor. The second argument accepts a few special characters: r for reading (default), w for writing, a for appending, r+ for reading and writing, b for binary mode. >>> f = file("filename.txt", 'r') Use the open() method. The first argument is the filename, the second is the mode. >>> f = open("filename.txt", 'rb') Use the open() method typically. The file() constructor is removed in Python 3.x. Note: when a file operation fails, an IOError exception is raised.

FILE INPUT There are a few ways to grab input from a file. f.read() Returns the entire contents of a file as a string. Provide an argument to limit the number of characters you pick up. f.readline() One by one, returns each line of a file as a string (ends with a newline). End-of-file reached when return string is empty. Loop over the file object. Most common, just use a for loop! >>> f = file("somefile.txt",'r') >>> f.read() "Here's a line.\nhere's another line.\n" >>> f.close() >>> f = file("somefile.txt",'r') >>> f.readline() "Here's a line.\n" >>> f.readline() "Here's another line.\n" >>> f.readline() '' >>> f.close() >>> f = file("somefile.txt",'r') >>> for line in f:... print(line)... Here's a line. Here's another line.

FILE INPUT Close the file with f.close() Close it up and free up resources. >>> f = open("somefile.txt", 'r') >>> f.readline() "Here s line in the file! \n" >>> f.close() Another way to open and read: No need to close, file objects automatically close when they go out of scope. with open("text.txt", "r") as txt: for line in txt: print line

STANDARD FILE OBJECTS Just as C++ has cin, cout, and cerr, Python has standard file objects for input, output, and error in the sys module. Treat them like a regular file object. import sys for line in sys.stdin: print line You can also receive command line arguments from sys.argv[ ]. for arg in sys.argv: print arg $ python program.py here are some arguments program.py here are some arguments

OUTPUT print or print() Use the print statement or 3.x-style print() function to print to the user. Use comma-separated arguments (separates with space) or concatenate strings. Each argument will be evaluated and converted to a string for output. print() has two optional keyword args, end and sep. >>> print 'Hello,', 'World', 2016 Hello, World 2016 >>> print "Hello, " + "World " + "2016" Hello, World 2016 >>> for i in range(10):... print i, # Do not include trailing newline... 0 1 2 3 4 5 6 7 8 9

PRINT FUNCTION Using the 3.x style print function is preferable to some people. print(*objects, sep=' ', end='\n', file=sys.stdout) Import with from future import print_function Specify the separation string using the sep argument. This is the character printed between comma-separated objects. Specify the last string printed with the end argument. Specify the file object to which to print with the file argument.

PRINT FUNCTION >>> from future import print_function >>> print(555, 867, 5309, sep="-") 555-867-5309 >>> print("winter", "is", "coming", end="...\n") Winter is coming... >>>

FILE OUTPUT f.write(str) Writes the string argument str to the file object and returns None. Make sure to pass strings, using the str() constructor if necessary. >>> f = open("filename.txt", 'w') >>> f.write("heres a string that ends with " + str(2017)) print >> f Print to objects that implement write() (i.e. file objects). f = open("filename.txt","w") for i in range(1, 11): print >> f, "i is:", i f.close()

MORE ON FILES File objects have additional built-in methods. Say I have the file object f: f.tell() gives current position in the file. f.seek(offset[, from]) offsets the position by offset bytes from from position. f.flush() flushes the internal buffer. Python looks for files in the current directory by default. You can also either provide the absolute path of the file or use the os.chdir() function to change the current working directory.

MODIFYING FILES AND DIRECTORIES Use the os module to perform some file-processing operations. os.rename(current_name, new_name) renames the file current_name to new_name. os.remove(filename) deletes an existing file named filename. os.mkdir(newdirname) creates a directory called newdirname. os.chdir(newcwd) changes the cwd to newcwd. os.getcwd() returns the current working directory. os.rmdir(dirname) deletes the empty directory dirname.

EXCEPTIONS Errors that are encountered during the execution of a Python program are exceptions. >>> print spam Traceback (most recent call last): File "<stdin>", line 1, in? NameError: name 'spam' is not defined >>> '2' + 2 Traceback (most recent call last): File "<stdin>", line 1, in? TypeError: cannot concatenate 'str' and 'int' objects There are a number of built-in exceptions, which are listed here.

HANDLING EXCEPTIONS Explicitly handling exceptions allows us to control otherwise undefined behavior in our program, as well as alert users to errors. Use try/except blocks to catch and recover from exceptions. >>> while True:... try:... x = int(raw_input("enter a number: "))... except ValueError:... print("ooops!! That was not a valid number. Try again.")... Enter a number: two Ooops!! That was not a valid number. Try again. Enter a number: 100

HANDLING EXCEPTIONS First, the try block is executed. If there are no errors, except is skipped. If there are errors, the rest of the try block is skipped. Proceeds to except block with the matching exception type. Execution proceeds as normal. >>> while True:... try:... x = int(raw_input("enter a number: "))... except ValueError:... print("ooops!! That was not a valid number. Try again.")... Enter a number: two Ooops!! That was not a valid number. Try again. Enter a number: 100

HANDLING EXCEPTIONS If there is no except block that matches the exception type, then the exception is unhandled and execution stops. >>> while True:... try:... x = int(input("enter a number: "))... except ValueError: Note our change to input here!... print("ooops!! That was not a valid number. Try again.")... Enter a number: 3/0 Traceback (most recent call last): File "<stdin>", line 3, in <module> File "<string>", line 1, in <module> ZeroDivisionError: integer division or modulo by zero

HANDLING EXCEPTIONS The try/except clause options are as follows: Clause form except: except name: except name as value: except (name1, name2): except (name1, name2) as value: else: finally: Interpretation Catch all (or all other) exception types Catch a specific exception only Catch the listed exception and its instance Catch any of the listed exceptions Catch any of the listed exceptions and its instance Run if no exception is raised Always perform this block

HANDLING EXCEPTIONS There are a number of ways to form a try/except block. >>> while True:... try:... x = int(raw_input("enter a number: "))... except ValueError:... print("ooops!! That was not a valid number. Try again.")... except (TypeError, IOError) as e:... print(e)... else:... print("no errors encountered!")... finally:... print("we may or may not have encountered errors ")...

RAISING AN EXCEPTION Use the raise statement to force an exception to occur. Useful for diverting a program or for raising custom exceptions. try: raise IndexError("Index out of range") except IndexError as ie: print("index Error occurred: ", ie) Output: Index Error occurred: Index out of range

CREATING AN EXCEPTION Make your own exception by creating a new exception class derived from the Exception class (we will be covering classes soon). >>> class MyError(Exception):... def init (self, value):... self.value = value... def str (self):... return repr(self.value)... >>> try:... raise MyError(2*2)... except MyError as e:... print 'My exception occurred, value:', e... My exception occurred, value: 4

ASSERTIONS Use the assert statement to test a condition and raise an error if the condition is false. is equivalent to >>> assert a == 2 >>> if not a == 2:... raise AssertionError()

EXAMPLE: PARSING CSV FILES Football: The football.csv file contains the results from the English Premier League. The columns labeled Goals and Goals Allowed contain the total number of goals scored for and against each team in that season (so Arsenal scored 79 goals against opponents, and had 36 goals scored against them). Write a program to read the file, then print the name of the team with the smallest difference in for and against goals. Solutions available in the original post. (Also, there s some nice TDD info). Credit: https://realpython.com/blog/python/python-interview-problem-parsing-csv-files/