Lecture 4 Python Basics Part 3.

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 Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Python’s input and output Chenghao Wang. Fancier Output Formatting – Output method ▪Print() ▪Str() ▪Repr() Example S=“Hello World” Print(s) OR Print(“Hello.
Structured programming
 2002 Prentice Hall. All rights reserved Exception-Handling Overview Exception handling –improves program clarity and modifiability by removing.
Exceptions COMPSCI 105 S Principles of Computer Science.
Floating point numbers in Python Floats in Python are platform dependent, but usually equivalent to an IEEE bit C “double” However, because the significand.
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.
WEEK EXCEPTION HANDLING. Syntax Errors Syntax errors, also known as parsing errors, are perhaps the most common kind of complaint you get while.
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Chapter 14 Files and Exceptions II. "The Practice of Computing Using Python", Punch & Enbody, Copyright © 2013 Pearson Education, Inc. What we already.
17. Python Exceptions Handling Python provides two very important features to handle any unexpected error in your Python programs and to add debugging.
Exceptions 2 COMPSCI 105 S Principles of Computer Science.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Functions Reading/writing files Catching exceptions
Guide to Programming with Python Chapter Seven (Part 1) Files and Exceptions: The Trivia Challenge Game.
Lecture 06 – Reading and Writing Text Files.  At the end of this lecture, students should be able to:  Read text files  Write text files  Example.
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 7 Files.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
1 Chapter 7 – Object-Oriented Programming and File Handling spring into PHP 5 by Steven Holzner Slides were developed by Jack Davis College of Information.
Exam 1 Review Instructor – Gokcen Cilingir Cpt S 111, Sections 6-7 (Sept 19, 2011) Washington State University.
Cem Sahin CS  There are two distinguishable kinds of errors: Python's Errors Syntax ErrorsExceptions.
Outline Overview Opening a file How to create a file ? Closing a File Check End-of-file Reading a File Line by Line Reading a File Character by Character.
Python Conditionals chapter 5
Artificial Intelligence Lecture No. 26 Dr. Asad Ali Safi ​ Assistant Professor, Department of Computer Science, COMSATS Institute of Information Technology.
Guide to Programming with Python Chapter Seven Files and Exceptions: The Trivia Challenge Game.
16. Python Files I/O Printing to the Screen: The simplest way to produce output is using the print statement where you can pass zero or more expressions,
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
11. EXCEPTION HANDLING Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
GAME203 – C Files stdio.h C standard Input/Output “getchar()”
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])
Firoze Abdur Rakib. Syntax errors, also known as parsing errors, are perhaps the most common kind of error you encounter while you are still learning.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
Exception Handling and String Manipulation. Exceptions An exception is an error that causes a program to halt while it’s running In other words, it something.
Python Exceptions and bug handling Peter Wad Sackett.
CIT 590 Intro to Programming Files etc. Agenda Files Try catch except A module to read html off a remote website (only works sometimes)
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
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.
C Programming Day 2. 2 Copyright © 2005, Infosys Technologies Ltd ER/CORP/CRS/LA07/003 Version No. 1.0 Union –mechanism to create user defined data types.
EXCEPTIONS. Catching exceptions Whenever a runtime error occurs, it create an exception object. The program stops running at this point and Python prints.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
George Mason University
Introduction to Python
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.
Lecture 4 Python Basics Part 3.
Taken from notes by Dr. Neil Moore & Dr. Debby Keen
Python’s input and output
Exceptions and files Taken from notes by Dr. Neil Moore
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Chapter 7 Files and Exceptions
Python’s Errors and Exceptions
Exceptions and files Taken from notes by Dr. Neil Moore
Lecture 4 Python Basics Part 3.
ERRORS AND EXCEPTIONS Errors:
File Input and Output.
(Oops! When things go wrong)
Advanced Python Concepts: Exceptions
G. Pullaiah College of Engineering and Technology
Topics Introduction to File Input and Output
Advanced Python Concepts: Exceptions
By Ryan Christen Errors and Exceptions.
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Presentation transcript:

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. >>> 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. Note: In Python 3.x, input() is now just raw_input().

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. Use the open() method. The first argument is the filename, the second is the mode. >>> f = file("filename.txt", 'r') >>> f = open("filename.txt", 'rb') Note: when a file operation fails, an IOError exception is raised. Use the open() method typically. The file() constructor is removed in Python 3.x.

File input There are a few ways to grab input from a file. f.read() >>> 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. 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!

File input Close the file with f.close() Another way to open and read: Close it up and free up resources. Another way to open and read: No need to close, file objects automatically close when they go out of scope. >>> f = open("somefile.txt", 'r') >>> f.readline() "Here’s line in the file! \n" >>> f.close() 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. You can also receive command line arguments from sys.argv[ ]. import sys for line in sys.stdin: print line 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', 2015 Hello, World 2015 >>> print "Hello, " + "World " + "2015" Hello, World 2015 >>> 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. Import with 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(*objects, sep=' ', end='\n', file=sys.stdout) from __future__ import print_function

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) print >> f Writes the string argument str to the file object and returns None. Make sure to pass strings, using the str() constructor if necessary. print >> f Print to objects that implement write() (i.e. file objects). >>> f = open("filename.txt", 'w') >>> f.write("Heres a string that ends with " + str(2015)) f = open("filename.txt","w") for i in range(1, 10 + 1): print >> f, 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(raw_input("Enter a number: ")) ... except ValueError: ... 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 Interpretation except: Catch all (or all other) exception types except name: Catch a specific exception only except name as value: Catch the listed exception and its instance except (name1, name2): Catch any of the listed exceptions except (name1, name2) as value: Catch any of the listed exception and its instance else: Run if no exception is raised finally: 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 (RuntimeError, 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)

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/