0% found this document useful (0 votes)
3 views14 pages

Chapter Three First Modules1

Chapter Three covers Python I/O, error handling, and exceptions. It discusses string functions, file operations, and the use of the pickle module for object serialization, along with exception handling techniques. The chapter also introduces input methods and string formatting, providing examples and best practices for each topic.

Uploaded by

galatasa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views14 pages

Chapter Three First Modules1

Chapter Three covers Python I/O, error handling, and exceptions. It discusses string functions, file operations, and the use of the pickle module for object serialization, along with exception handling techniques. The chapter also introduces input methods and string formatting, providing examples and best practices for each topic.

Uploaded by

galatasa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter Three

PYTHON I/O , ERROR HANDLING


AND EXCEPTIONS
TODAY’S PLAN

dir()
Strings in Python
input and raw_input
File I/O, pickle
Exception Handling
Milestone 1 overview
WHAT’S DIR FOR?

Gives a sorted list of the names defined in a module

Examples to try:
>>> import sys
>>> dir(sys)
>>> dir()
>>> dir( builtins )
two underbars each

Q1
SOME STRING FUNCTIONS

s = „Hello‟ [Link](„ello‟, „i‟)


[Link]() „a,b,c‟.split(„,‟)
[Link](30,„X‟) [Link](„H‟)
[Link](„lo‟) [Link](), also lstrip, rstrip
[Link](20), also rjust
Try: help(str)
[Link]()
Q2
STRING FORMATTING

% operator on strings → deprecated

Use format method on strings:


"{0:4d} {1:4d}".format(42*2, 42**2) → ' 84 1764'

"{1:5d} {0:5d}".format(42*2, 42**2) → ' 1764 84'

"{0:5.2f} {1} {2}".format(sqrt(42), 'sheep', 'plummet')


→ ' 6.48 sheep plummet'

Q3
NAMED FORMAT
ARGUMENTS
"X Coord.: {x:.2f},Y Coord.: {y:.2f}".format(x=3.145, y=2.71)
→ 'X Coord.: 3.15,Y Coord.: 2.71'

d={'phone':8793, 'fax':6060}
"Phone {0[phone]} or fax {0[fax]}".format(d)
→ 'Phone 8793 or fax 6060'

x, y = 3.2, 5.4
"{x:5.2f}{y:5.2f}".format(**vars())
→ ' 3.20 5.40'

What does vars() return?

Q4
INPUT AND RAW_INPUT

input(prompt)

Displays prompt, accepts console input, returns it


as a string
raw_input(prompt) is gone in Python 3
SPEAKING OF INPUTS

[Link]

Her daughter is named


Help I‟m trapped in a driver‟s license factory.
FILE I/O

Opening: f = open(file_path, mode)

file_path is the path to the file (duh!)


mode is the access mode: „r‟,„w‟,„a‟,„r+‟, „rb‟,„wb‟
Writing: [Link](„String to write‟) reading and
writing

Closing: [Link]()
READING FROM
AN OPEN FILE

[Link](), returns entire contents of file

[Link](), returns next line of file


[Link](), returns entire contents as a list of strings
Often better to iterate over file:

for line in f:
# do something with line
FILE I/O WITH WITH

Files (and others) can clean up after themselves


Example:
with open(“[Link]”,„r‟) as f:
for line in f:
# do something with line
with statement automatically closes file

Q5
GETTING PICKLED

The pickle module converts objects to/from streams


[Link](obj, file)
Note: File must
obj = [Link](file) be opened in
What can be pickled? (partial list) binary mode
None, True, False, numbers, and strings
tuples, lists, sets, dictionaries of picklable things

Q6
EXCEPTION HANDLING

try:
# Code that might raise an exception
except ExceptionType [as var]:
# Handles ExceptionType
except OtherExceptionType [as var]:
# Handles OtherExceptionType Generally
except: frowned upon
# Handles any other exceptions
else:
# Runs if no exceptions
finally:
# Runs no matter what happened above
Q7
EXCEPTION ARGUMENTS

try:
raise Exception('spam','eggs')
except Exception as inst:
print(type(inst)) <class 'Exception'>
print([Link]) ('spam', 'eggs')
print(inst) ('spam', 'eggs')
x, y = [Link]
print('x = {}, y = {}'.format(x,y))
x = spam, y = eggs

See docs for defining your


own exception types

You might also like