IT 116: Introduction to Scripting
Class 22
Tips and Examples
Review
New Material
Microphone
Questions
Are there any questions before I begin?
Homework 10
I have posted homework 10
here.
It is due this coming Sunday at 11:59 PM.
Readings
If you have the textbook you should read Chapter 7,
Lists and Tuples, from
Starting Out with Python.
Graded Quiz Today
After I finish talking I will pass out the papers for
today's graded quiz.
Write your name clearly at the top.
When you finish the Quiz hand it to me.
Then you can work on the Class Exercise and today's ungraded quiz.
Tips and Examples
All Scripts Must Be Executable
- Many of you have forgotten to make your scripts executable
- If you forget to do this you will lose points on assignments
- There are two things you have to do to make a script executable
- Give the script read and execute permissions
- Write the hashbang line on the very first
line of the script
- You can change the permissions in FileZilla
- Once you have transfered the file to
pe15.cs.umb.edu ...
- right click on the file to bring up a menu ...
- and enter 755 in the Permissions box
- You can also do this on the Unix command line like this
chmod 755 FILENAME
- The hashbang line must be the very first line in the script
- It should be
#! /usr/bin/python3
Review
The Code in the try Clause
- A call to
open must always be put inside the
try block ...
- of a
try/except statement
- But if the rest of your code needs the file object to function properly ...
- it must be but in a place wher it will not run if an exception occurs
- The code below does not do this ...
- and we get a runtime error
filename = input("Filename: ")
try:
file = open(filename, "r")
except:
print("Cannot open", filename)
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print("Average:", average)
$ ./temps_average_3.py
Filename: xxx
Cannot open xxx
Traceback (most recent call last):
File "./temps_average_3.py", line 15, in <module>
for line in file:
NameError: name 'file' is not defined
- There is more than one way to deal with this issue
- One way is to put all the code that needs the file object ...
- inside the
try block
Different Exception Types
- A runtime error makes the interpreter create an exception object
- When this happens the interpreter is said to
raise an exception
- The exception mechanism has three purposes
- To allow the interpreter to handle the runtime error
- To give the programmer some idea of what went wrong
- To give the programmer the chance to do something
about it
- There is more than one way to cause a runtime error
- So different exception objects are created for different runtime errors
Common Exception Types
- When you try to open a file that does not exists ...
- the interpreter creates
FileNotFoundError exception object
>>> open("xxx.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'xxx.txt'
- If you try to open a file for which you do not have permission ...
- a PermissionError object will be created
file = open("test.txt","r")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
PermissionError: [Errno 13] Permission denied: 'test.txt'
- If a conversion function gets an argument of the wrong data type ...
- a TypeError object is created
>>> round("foo")
Number: foo
File "<stdin>", line 1, in <module>
TypeError: type str doesn't define __round__ method
- If you give a function a value it can't handle ...
- a ValueError object is created
>>> number = float(input("Number: "))
Number: 5..4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: could not convert string to float: '5..4'
- If you try to divide by zero ...
- the interpreter will create a
ZeroDivisionError exception object
>>> print(5/0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
Handling More Than One Type of Exception
- You can have many
except clauses in a
try/except statement
- One for each exception type
- The format is
try:
STATEMENT
...
except EXCEPTION_TYPE_1:
STATEMENT
...
except EXCEPTION_TYPE_2:
STATEMENT
...
...
- You can catch as many exception types as you want
- This format can be used to create an improved version of
open_file_read
def open_file_read():
while True:
filename = input("Filename: ")
try:
file = open(filename, "r")
return file
except FileNotFoundError:
print("Cannot find", filename)
except PermissionError:
print("You do not have permission to read", filename)
The else Clause
- A
try/except statement can also have an
else clause
- Code in an
else block runs if there is no runtime error
- Only put code that can cause a runtime error in the
try
block
- Put any code that depends on the
try block statements
working properly ...
- in an
else block
try:
file = open(filename, "r")
except:
print("Cannot open", filename)
else:
count = 0
total = 0
for line in file:
count += 1
date, temp = line.split()
temp = int(temp)
total += temp
average = round(total/count, 2)
print("Average:", average)
The finally Clause
- There is another type of clause that can occur a
try/except statement
- It has the format
finally:
STATEMENT
....
- The statements in a
finally clause will always be executed
- It does not matter whether a runtime error occurs
- We will not have to use this feature of Python
- But in more advanced scripts it can be useful
- The
finally clause allows you to clean up any lose ends ...
- no matter what happens when the script is run
Attendance
New Material
Working with Collections of Data
- A variable holds one piece of information
- For simple tasks, that's all we need
- But for many tasks we need to work with collections of data
- For example, a list of all the students in a class
- Or all the scores on a quiz
- To work with data like this we need
data types
...
-
that can hold many pieces of information
Sequences
- Python has a class of data types called
sequences
- Sequences can hold multiple values ...
- stored one right after the other in RAM ...
- Like this
- The values are stored in particular order
- Today I will discuss two sequence data types
- Lists are sequences whose values can be changed
- Tuples are sequences that cannot be changed
- A list or tuple is an object
- This means they have
methods
- Methods are functions that work on the values in an object
Lists
- Lists can hold many values ...
- in a specific order
- The values are called
elements
- They are stored in RAM one right after the other
- You can change any value in the list
- You can also change their order ...
- and add and remove items from the list
- A list
literal
is written using square brackets
- Inside the the brackets are different values
- Separated by commas
>>> even_numbers = [2, 4, 6, 8, 10]
>>> even_numbers
[2, 4, 6, 8, 10]
- Here is what this looks like in memory
- even_numbers is a variable ...
- that contains the address of the list object
- You can say it points to the list object
- Lists can contain strings
>>> courses = ["IT 244", "IT 341", "IT 116"]
>>> courses
['IT 244', 'IT 341', 'IT 116']
- They can hold
float values
>>> expenses = [37.55, 21.25, 32.00]
>>> expenses
[37.55, 21.25, 32.0]
- They can hold boolean values
>>> results = [True, False, True]
>>>results
[True, False, True]
- They can also hold values of different types
>>> python_class = ["IT 116", 32, "McCormack 2-621"]
>>> python_class
- You can even have lists of lists
>>> lists = [ numbers, results, expenses]
>>> lists
[[5, 8, 2, 9, 7, 6, 3], [True, False, True], [37.55, 21.25, 32.0]]
The list Function
- List literals are only one way to create lists
- Another way is to use the built-in function
list
list is a conversion function just like int and
str
list turns objects that are collections of values into a list
- It turns out that strings are also sequences
- A string is a collection of characters one right after the other
- So we can use
list on strings
>>> name = "Glenn"
>>> characters = list(name)
>>> characters
['G', 'l', 'e, 'n', 'n']
- Why is there a separate data type for strings?
- Because string objects have methods that only work on characters
>>> name.upper()
'GLENN'
>>> name.lower()
'glenn'
Using a for Loop with Lists
for loops will work with any sequence object
- Like a list
>>> numbers = [1, 2, 3, 4, 5]
>>> for n in numbers:
... print(n)
...
1
2
3
4
5
- When we use a loop to work with each value in a sequence
- We are said to
iterate
over that sequence
- We can also use a
for loop with strings
>>> team = "Red Sox"
>>> for char in team:
... print(char)
...
R
e
d
S
o
x
>>>
- Because strings are sequences
Empty Lists
The len Function
- The built-in function
len will return the length of any sequence
>>> even_numbers = [2, 4, 6, 8, 10]
>>> len(even_numbers)
5
>>> len("foo")
3
The min and max Functions
- The two
built-in functions
min and max ...
- can also be used with lists
- They do not change the list
- But they return information about it
min returns the smallest value in a list
>>> l6
[1, 4, 5, 6]
>>> min(l6)
1
max returns the largest
max(l6)
6
- But
minand max only work on lists ...
- where all the elements can be ordered
- They won't work on lists like this
>>> l1 = [1, "one", 2, "two", 3, "three"]
>>> max(l1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '<' not supported between instances of 'str' and 'int'
>>> max(l1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>' not supported between instances of 'str' and 'int'
Creating Lists from Files
- In previous scripts we sometimes had to read through a file twice
- We did this when we found the number of days with temperatures above average
- We had to read through the file once to calculate the average
- Then read through it again to find the days above average
- Operations with files are much slower than operators in RAM
- So reading a file twice is very inefficient
- It turns out we don't have to do this
- We can read in a file once, storing the lines in a list
- The list is stored in RAM so working with it is very fast
- To create a list from a file we first create an empty list
- Then we read through the file adding each line to the list
- Lists are objects
- So they have methods that can operate on their values
- We can add something to a list by using the append
method
- append adds it's argument to the end of
the list
- Here is a script that creates a list from a file
file = open("numbs.txt","r")
numbs = []
for line in file:
num = int(line)
numbs.append(num)
print(numbs)
- Running this script I get
$ ./list_from_file.py
[46, 19, 35, 43, 35, 33, 42]
Honesty and Trust
Class Exercise
Class Quiz