for
Looppython3
python3
try
Clauseelse
Clausefor
Loop with Listslen
Functionin
Operatordel
Statementfor
Loop with StringsThe final exam will be given on Thursday, May 21st. It will be on Blackboard. I will use the same format as the Midterm. The exam will be a two parts exam (Questions and writing short segments of Python code).
The last day of our class will be on Tuesday, May 12th, We will have an optional Zoom meeting for any question you may have. I will send you the Zoom information.
Class 28, on Thursday, May 7th, will be a review session.
You will only be responsible for the material in Class Notes 28 and the review for the Mid-term, which you will find here.
The final will be an online exam.
>>> 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
$ cat random_1.py # demonstrates the use of the randint function of the random module import random for i in range(10): print(random.randint(1,100)) $ python3 random_1.py 89 98 93 73 32 40 63 100 76 80 $ python3 random_1.py 66 49 1 29 63 17 91 3 70 5
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 filepython3
then executes all the Python statements in the file# prints a friendly message print("Hello world!")
$ python3 hello_1.py Hello world!
python3
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, the interpreter stops executing the rest of the code
except
code block and executes those statementsopen
to create a file you should
put it inside a 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 string so we need to use a conversion functionint
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
statement
you will get an 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
open
statement working try
/except
statement
else
Clausetry
/except
statement can also have an else
clausetry
block code does not
cause a runtime error
try
clause to
work inside an 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)
>>> numbers = [5, 8, 2, 9, 7, 6, 3] >>> numbers [5, 8, 2, 9, 7, 6, 3]
>>> 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
>>> tuple_1 = (1, 2, 3, 4, 5) >>> tuple_1 = (1, 2, 3, 4, 5) (1, 2, 3, 4, 5)
>>> tuple_2 = (1, 2.5, False, "Sam") >>> tuple_2 (1, 2.5, False, 'Sam')
>>> tuple_1[0] 1
for
loop to print all the elements
>>> for number in tuple_1: ... print(number) ... 1 2 3 4 5
>>> 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