I&C SCI 32 Chapter Notes - Chapter 1: Local Variable, Empty String, Hard Disk Drive

97 views19 pages
# oops.py
#
# ICS 32 Fall 2015
# Code Example
#
# This module contains a Python program that always crashes. Run this
# module and take a look at its output (a traceback). A valuable skill
# as a Python programmer is the ability to read a traceback and use it
# to help diagnose the cause of unexpected crashes.
def f():
x = 3
g(x)
def g(n):
print(len(n))
if __name__ == '__main__':
f()
# line_count.py
#
# ICS 32 Fall 2015
# Code Example
#
# This module demonstrates a function that raises an exception and another
# function that catches it. The program, overall, counts the number of
# lines of text in a text file, by separating the program's functionality
# into self-contained parts:
#
# * A function that takes the path to a file and returns the number of
# lines of text in it.
#
# * A function that acts as a user interface, both taking input from the
# user and printing output. All user interaction happens there.
#
# * A "main" block that makes the module executable as a program.
#
# It also makes a conscious, good choice about the use of memory: rather
# than reading the entire file into memory just so we can count the number
# of lines, we instead read the file one line at a time and count the lines
# as we go. Even though we've written more code, the program, overall, is
# probably doing roughly the same amount of work; it's just that we're doing
# a little more and the Python library is doing a little less. But the end
# result is much better, because our program is capable of handling files of
# any size, no matter how little memory we have available to us -- unless the
# entire contents of a very large file are all on a single line (and if we
# were worried about that, we could read the file even more carefully, a
# few characters at a time, and count newline characters).
# count_lines_in_file() takes the path to a file and returns an
# integer specifiying the number of lines of text in that file.
#
# Notice that this function does not catch any exceptions, but that it
# still has a "try" statement with a "finally" clause. That's because
# we're using the "finally" clause to ensure that the file is closed, if
# it was successfully opened, no matter what happens. (For example,
# any of the calls to readline() could raise exceptions. If so, the
# file will have been opened, so we'll want to ensure it gets closed.
# Or no exceptions might be raised, in which case we still want to be
# sure it gets closed. A "finally" clause ensures both.)
def count_lines_in_file(file_path: str) -> int:
'''
Given the path to a file, returns the number of lines of text in
that file, or raises an exception if the file could not be opened.
'''
the_file = None
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 19 pages and 3 million more documents.

Already have an account? Log in
try:
the_file = open(file_path, 'r')
line_count = 0
# A "for" loop, when used to iterate over a file, runs one loop
# iteration for each line of text in the file.
for line in the_file:
line_count += 1
return line_count
finally:
if the_file != None:
the_file.close()
# An interesting question to ask at this point is why count_lines_in_file
# doesn't catch exceptions, but instead steps aside and lets its caller
# handle them instead.
#
# Think about the function's job: it takes the path to a file and returns
# the number of lines of text in that file. And here's the important
# thing: it can't possibly know where that path came from. This function
# might be called by the user_interface() function below. But it might also
# be called from the interpreter, or from code in another module. There
# might have been a human user, but there might not. This function's role
# is best kept simple, so it shouldn't make any assumptions about what its
# callers do.
#
# Given that, now we have to ask ourselves another question. If this
# function doesn't assume anything about where its parameter came from,
# what can it possibly do if the parameter is the path to a file that
# doesn't exist or can't otherwise be opened? It can't ask the user for
# another path, because there may not be a user. It can't guess about
# what other file it might try, because there's no reasonable guess.
# All it can do is say "Well, I tried, but I failed!" Failure to open
# the file is failure to count the number of lines in it, pure and
# simple. In Python, that means it should step aside and let any
# exception propagate to its caller, who might be more aware of the
# broader context (e.g., is there a user?) and can do something appropriate.
# This user_interface() function provides a simple, console-mode
# user interface that allows the user to choose a file and then
# prints how many lines of text are in the file.
#
# Here, we're catching the exception raised in count_lines_in_file(),
# because this function is aware of the broader context. There is a
# user and interaction is being done via the console. So an appropriate
# thing to do might be to print an error message.
def user_interface() -> None:
'''
Repeatedly asks the user to specify a file; each time, the number of
lines of text in the file are printed, unless the file could not be
opened, in which case a brief error message is displayed instead.
'''
while True:
file_path = input('What file? ').strip()
if file_path == '':
break
try:
lines_in_file = count_lines_in_file(file_path)
print('{} line(s) in {}'.format(lines_in_file, file_path))
except:
print('Failed to open and/or read the file successfully')
# I should point out here that printing an error message to the console
# is not always what you do when you catch an exception, though it turned
# out to be reasonable enough in this example. We'll see plenty of examples
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 19 pages and 3 million more documents.

Already have an account? Log in
# where something else is more appropriate.
if __name__ == '__main__':
user_interface()
# sum_numbers1.py
#
# ICS 32 Fall 2015
# Code Example
#
# This function sums the numbers in a flat list of integers. By "flat list",
# I mean that the list no sublists (i.e., every element is an integer).
def sum_numbers(numlist: [int]) -> int:
'''Adds up the integers in a list of integers'''
total = 0
for num in numlist:
total += num
return total
assert(sum_numbers([1, 2, 3, 4, 5]) == 15)
assert(sum_numbers([5, 8, 9, 3]) == 25)
assert(sum_numbers([4]) == 4)
assert(sum_numbers([]) == 0)
# sum_numbers2.py
#
# ICS 32 Fall 2015
# Code Example
#
# This function sums the integers in a list of *lists* of integers.
def sum_numbers(numlist: [[int]]) -> int:
'''Adds up the integers in a list of lists of integers'''
total = 0
for sublist in numlist:
for num in sublist:
total += num
return total
assert(sum_numbers([[1, 2], [3, 4], [5, 6, 7]]) == 28)
assert(sum_numbers([[1], [2], [3, 4, 5]]) == 15)
assert(sum_numbers([[3], [], [5]]) == 8)
assert(sum_numbers([[1, 2]]) == 3)
assert(sum_numbers([[9]]) == 9)
assert(sum_numbers([]) == 0)
# sum_numbers3.py
#
# ICS 32 Fall 2015
# Code Example
#
# This function sums the integers in a list containing *either* integers
# of sublists that are flat lists of integers.
#
# One interesting new tidbit here that you might not have seen is that you
# check the type of an object. type(x) is a function that returns the
# type of the object x; you can compare types using == the same way you
# can compare other kinds of objects. We use that to check whether an
# object is a list, like this:
#
find more resources at oneclass.com
find more resources at oneclass.com
Unlock document

This preview shows pages 1-3 of the document.
Unlock all 19 pages and 3 million more documents.

Already have an account? Log in

Document Summary

# this module contains a python program that always crashes. # module and take a look at its output (a traceback). # as a python programmer is the ability to read a traceback and use it. # to help diagnose the cause of unexpected crashes. def f(): x = 3 g(x) def g(n): print(len(n)) if __name__ == "__main__": f() # this module demonstrates a function that raises an exception and another. # lines of text in a text file, by separating the program"s functionality. # * a function that takes the path to a file and returns the number of. # * a function that acts as a user interface, both taking input from the. # * a main block that makes the module executable as a program. # it also makes a conscious, good choice about the use of memory: rather. # than reading the entire file into memory just so we can count the number.

Get access

Grade+
$40 USD/m
Billed monthly
Grade+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
10 Verified Answers
Class+
$30 USD/m
Billed monthly
Class+
Homework Help
Study Guides
Textbook Solutions
Class Notes
Textbook Notes
Booster Class
7 Verified Answers

Related Documents