for
Looppython3
try
Clauseelse
Clausefor
Loop with Listslen
Functionin
Operatordel
Statementfor
Loop with StringsThe final exam will be held on Tuesday, December 19th from 3:00 to 6:00 PM..
The exam will be given in this room.
If for some reason you are not able to take the Final at the time it will be offered, you MUST send an email to me before the exam so we can make alternative arrangements.
The final will consist of questions like those on the quizzes, along with questions asking you to write short segments of Python code.
60% of the points on this exam will consist of questions from the Ungraded Class Quizzes.
The remaining 40% will come from 4 questions that ask you to write some code.
To study for the code questions you should be able to
A good way to study for the code questions is to review the Class Exercises homework solutions and Class Notes.
The last class on Thursday, December 7th, will be a review session.
You will only be responsible for the material in that review session and the review for the Midterm, which you will find here.
Although the time alloted for the exam is 3 hours, I would expect that most of you would not need that much time.
The final is a closed book exam.
To prevent cheating, certain rules will be enforced during the exam.
At the end of each semester we offer you the opportunity to say what you think about this course.
What have I done right?
What have I done wrong?
What can I do better?
You are not asked for you name.
So the submissions are anonymous.
I will not see your responses until after I have submitted grades for this course.
We collect this feedback through Course Evaluations.
I will use what you say to make this course better.
To complete the course evaluation, use the following link .
You have until Friday, December 22nd, to submit the evaluation.
If you do not complete the course evaluation by this date, I will subtract 1 point from the your weighted score, which determines your grade.
Are there any questions before I begin?
>>> result = round(8.765)
>>> result
9
return EXPRESSION
return
statement does two things
return
statement can return more than one value
return EXPRESION, EXPRESSION [, EXPRESSION, ...]
>>> def get_full_name(): ... first_name = input("Please enter your first name: ") ... last_name = input("Please enter your last name: ") ... return first_name, last_name ...
>>> fname, lname = get_full_name() Please enter your first name: Glenn Please enter your last name: Hoffman
open
open
function does two things
open
function
FILE_VARIABLE = open(FILENAME, MODE)
Mode | Description |
---|---|
"r" | Open a file for reading only |
"w" | Open a file for writing |
"a" | Open a file for writing to the end of the file |
OBJECT_VARIABLE.METHOD_NAME
teams_file = open("teams.txt", "w")
$ cat write_teams.py # writes the names of the teams in the American League East teams_file = open("teams.txt", "w") teams_file.write("Boston Red Sox\n") teams_file.write("Baltimore Orioles\n") teams_file.write("Toronto Blue Jays\n") teams_file.write("Tampa Bay Rays\n") teams_file.write("New York Yankees\n") $ python3 write_teams.py $ cat teams.txt Boston Red Sox Baltimore Orioles Toronto Blue Jays Tampa Bay Rays+ New York Yankees
for
Loopfor
loopfor
loop has this format
for LOOP_VARIABLE in LIST_OF_SOME_KIND:
for line in file: print(line.rstrip())
python3
python3
at the command line we are running this
binary file
python3
then executes all the Python statements in the file# prints a friendly message print("Hello world!")
$ python3 hello_1.py Hello world!
python3
chmod
command
chmod 755 FILENAME
#! /usr/bin/python3
>>> name = "Glenn"
>>> print(nme)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'nme' is not defined
average = num_1 + num_2 / 2 print ("Average:", average)
$ ./file_open.py
Filename: xxxxxx
Traceback (most recent call last):
File "./file_open.py", line 6, in <module>
file = open(filename, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'xxxxxx'
try
/except
statement which has
the following form
try:
STATEMENT
STATEMENT
...
except:
STATEMENT
STATEMENT
...
try
code block
causes a runtime error
except
code block and executes those
statements
open
to create a file
try
/except
statement$ cat open_file.py #! /usr/bin/python3 # demonstrates using a try/except statement # to catch exceptions encountered while # trying to open a file filename = input("Filename: ") try: file = open(filename, "r") for line in file: print(line.rstrip()) except: print("Could not open file", filename) $ ./open_file.py Filename: xxxx Could not open file xxxx
for
loopinput
to ask the user for a numberinput
returns a stringint
and float
can cause a runtime errortry
/except
statementwhile
loopdef get_integer(): while True: number = input("Integer: ") try: number = int(number) return number except: print(number, "cannot be converted into an integer")
try
Clauseopen
statement
in the try
block of a try
/except
statement
try
/except
statementfilename = 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
open
statement working try
/except
statement else
Clausetry
/except
statement can also have an
else
clause
try
block code does not cause a runtime errortry
clause to work
else
clause
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)
>>> even_numbers = [2, 4, 6, 8, 10] >>> even_numbers [2, 4, 6, 8, 10]]
>>> name = "Glenn" + " " + "Hoffman" >>> name 'Glenn Hoffman'
>>> n1 = [1,2,3] >>> n2 = [4,5,6] >>> n1 + n2 [1, 2, 3, 4, 5, 6]
>>> n1 / n2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'list'
>>> zeros = [0] * 5 >>> zeros [0, 0, 0, 0, 0] >>> numbers = [1, 2, 3] * 3 >>> numbers [1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> "Go " * 3 'Go Go Go '
for
Loop with Listsfor
loop will work with a list
>>> numbers = [1, 2, 3, 4, 5] >>>for n in numbers: ... print(n) ... 1 2 3 4 5
for
loop with strings
>>> team = "Red Sox" >>> for char in team: ... print(char) ... R e d S o x >>>
>>> even_numbers[0] 2 >>> even_numbers[1] 4 >>> even_numbers[2] 6
len
Functionlen
will return the length of any sequence
>>> even_numbers = [2, 4, 6, 8, 10] >>> len(even_numbers) 5 >>> len("foo")
len
with range
to iterate through a list
for i in range(len(even_numbers)): ... print(even_numbers[i]) ... 2 4 6 8 10
numbers = [1, 4, 6, 8]
>>> numbers[0] = 2 >>> numbers [2, 4, 6, 8]
for
loop to change every element inside a
list
>>> for i in range(len(numbers)): ... numbers[i] += 1 ... >>> numbers [3, 5, 7, 9]
>>> new_list = [] >>> new_list []
in
Operatorin
is an operator that works on objects
that are a collection of values
VALUE in LIST
in
operator returns True
if the
LIST contains VALUE
False
>>> digits [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] >>> 1 in digits True >>> 11 in digits False
Method | Description |
---|---|
append(item) | Adds item to the end of the list |
sort() | Sorts the items in the list so they appear in ascending order (from the lowest value to the highest value) |
reverse() | Reverses the order of the items in the list |
>>> teams = [] >>> teams []
>>> teams.append("Red Sox") >>> teams ['Red Sox']
>>> teams.append("Orioles") >>> teams.append("Blue Jays") >>> teams.append("Rays") >>> teams.append("Yankees")
>>> teams ['Red Sox', 'Orioles', 'Blue Jays', 'Rays', 'Yankees']
>>> l2 = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3] >>> l2 [9, 1, 0, 2, 8, 6, 7, 4, 5, 3] >>>l2.sort() >>> l2 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l3 = [5, 4, 3, 2, 1] >>> l3.reverse() >>> l3 [1, 2, 3, 4, 5] >>> l3.reverse() >>> l3 [5, 4, 3, 2, 1]
>>> l4 = [2, 5, 9, 1, 8, 6, 3, 7, 4] >>> l4.sort() >>> l4 [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l4.reverse() >>> l4 [9, 8, 7, 6, 5, 4, 3, 2, 1]
del
Statementdel
statement
del LIST_VARIABLE[INDEX]
del
comes the list variable and the index
inside square brackets
>>> l5 = [1, 2, 3, 4, 5, 6] >>> del l5[2] >>> l5 [1, 2, 4, 5, 6]
min
returns the smallest value in a list
>>> l6 [1, 4, 5, 6] >>> min(l6) 1
max
returns the largest
max(l6) 6
create an empty list
for each line in the file:
append the line to the empty list
file = open("numbs.txt", "r") total = 0 numbers = [] for line in file: num = int(line) numbers.append(num) total += num
>>> team = "Red Sox"
>>> team[0] 'R'
for
Loop with Stringsfor
loop
>>> for ch in team: ... print(ch) ... R e d S o x
>>> def character_count(string, char): ... count = 0 ... for ch in string: ... if ch == char: ... count += 1 ... return count ... >>> character_count("Mississippi", "i") 4 >>> character_count("Mississippi", "s") 4 >>> character_count("Mississippi", "p") 2
for
loop to reverse a string
>>> def string_reverse(string): ... new_string = " ... for ch in string: ... new_string = ch + new_string ... return new_string ... >>> string_reverse("Mississippi") 'ippississiM' >>> string_reverse("radar") 'radar'
>>> string_1 = "Red" >>> string_1 = string_1 + " Sox" >>> string_1 'Red Sox'
string_1 += " Sox"two things are happening
Method | Description |
---|---|
lower | Returns a copy of the string with all alphabetic letters
converted to lowercase. Any character that is already lowercase, or is not an alphabetic letter, is unchanged. |
upper | Returns a copy of the string with all alphabetic letters
converted to uppercase. Any character that is already uppercase, or is not an alphabetic letter, is unchanged. |
lstrip | Returns a copy of the string with leading characters
removed. When run without an argument, it removes leading whitespace characters. When run with an argument, removes those characters. |
rstrip | Returns a copy of the string with all trailing
characters removed. When run without an argument, it removes tailing whitespace characters. When run with an argument, removes those characters. |
strip | Returns a copy of the string with leading and trailing
characters removed. When run without an argument, it removes leading and tailing whitespace characters. When run with an argument, removes those characters. |
>>> s = "foo bar bletch" >>> s.split() ['foo', 'bar', 'bletch']
>>> date = "2021-05006" >>> date.split("-") ['2021', '05006']