python3else Clauselen Functionfor Loop with Sequencesfor Loopin Operatordel StatementDoes anybody have any questions before I begin?
I have posted homework 2 here.
It is due this coming Sunday at 11:59 PM.
Today I will finish the review of the material covered in IT 116.
$ ~ghoffman/it117_test/ex04.sh
Unix username: ghoffman
ghoffman Glenn Hoffman
++++++++++++++++++++++++++++++++++
Is file executable?
----------------------------------
ex4.py is executable
----------------------------------
++++++++++++++++++++++++++++++++++
Looking for hashbang
----------------------------------
#! /usr/bin/python3
----------------------------------
++++++++++++++++++++++++++++++++++
Error check
----------------------------------
Traceback (most recent call last):
File "/courses/it117/s23/ghoffman/ghoffman/ex/ex4/ex4.py", line 85, in >module<
number_list = read_integers_into_list("numbers.txt")
File "/courses/it117/s23/ghoffman/ghoffman/ex/ex4/ex4.py", line 43, in read_integers_into_list
file = open(filename, "r")
FileNotFoundError: [Errno 2] No such file or directory: 'numbers.txt'
SYNTAX ERROR
ghoffman Glenn Hoffman
Class Exercise 4
python3
$ cat hello.py
print("Hello world!")
chmod command
$ chmod 755 hello_1.py $ ls -l hello_1.py -rwxr-xr-x 1 ghoffman faculty 50 Mar 13 21:58 hello_1.py
$ ./hello_1.py
./hello_1.py: line 3: syntax error near unexpected token `"Hello world!"
./hello_1.py: line 3: `print("Hello world!")'
$ cat hello2.py
#! /usr/bin/python3
# prints a friendly message
print("Hello world!")
python3 command
$ ./hello_2.py Hello world!
python3#! /usr/bin/python3
2016-04-04 Red Sox @ Astros Win 7-5 2016-04-05 Red Sox @ Astros Win 2-1 2016-04-07 Red Sox vs Yankees Loss 7-9
>>> for = 5
File "<stdin>", line 1
for = 5
^
SyntaxError: invalid syntax
>>> 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'
$ ./file_open.py
Filename: unreadable.txt
Traceback (most recent call last):
File "./file_open.py", line 6, in <module>
file = open(filename, "r")
PermissionError: [Errno 13] Permission denied: 'unreadable.txt'
try/except statement which has the following form
try:
STATEMENT
STATEMENT
...
except:
STATEMENT
STATEMENT
...
try
code block
causes a runtime error ...
try blockexcept code block ...open can cause a runtime error ...open statements inside a try
block
$ cat open_file.py
#! /usr/bin/python3
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 loopelse Clausetry/except statement can also have an
else clause
try block code does not cause a runtime
error
open is followed by
statements ...
try blockexcept block
try:
file = open(filename, "r")
except:
print("Could not open file", filename)
else:
for line in file:
print(line.rstrip())
>>> list_1 = [1,2,3,4,5] >>> tuple_1 = (1,2,3,4,5) >>> string_1 = "12345" >>> list_1[0] 1 >>> tuple_1[1] 2 >>> string_1[2] '3'
>>> [1,2,3] + [4,5] [1, 2, 3, 4, 5] >>> (1,2,3) + (4,5) (1, 2, 3, 4, 5) >>> "123" + "45" '12345'
>>> [1,2,3] * 2 [1, 2, 3, 1, 2, 3] >>> (1,2,3) * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> "123" * 4 '123123123123'
>>> empty_list = [] >>> empty_list [] >>> empty_tuple = () >>> empty_tuple () >>> empty_string = "" >>> empty_string "
>>> empty_list + [1] [1] >>> empty_tuple + (1,2) (1, 2) >>> empty_string + "123" '123'
len Functionlen ...
>>> len([1,2,3])
3
>>> len((1,2,3,4))
4
>>> len("1234")
4
for Loop with Sequencesfor loops make it easy to work with the elements of a sequence
for LOOP_VARIABLE in SEQUENCE:
>>> list_1 = [1,2,3] >>> for element in list_1: ... print(element) ... 1 2 3 >>> tuple_1 = (1,2,3) >>> for element in tuple_1: ... print(element) ... 1 2 3 >>> string_1 = "123" >>> for element in string_1: ... print(element) ... 1 2 3
for Loopfor loop
for INDEX_VARIABLE in range(len(LIST)):
LIST[INDEX_VARIABLE] = NEW_VALUE
>>> numbs = [1,2,3,4,5] >>>for index in range(len(numbs)): ... numbs[index] += 1 ... >>> numbs [2, 3, 4, 5, 6]
SEQUENCE_VARIABLE[FIRST_INDEX:ONE_MORE_THAN_LAST_INDEX]
>>> list_1 = [1,2,3,4,5] >>> list_1[2:4] [3, 4] >>> tuple_1 = (1,2,3,4,5) >>> tuple_1[0,4] >>> tuple_1[0:4] (1, 2, 3, 4) >>> string_1 = "12345" >>> string_1[2:6] '345'
>>> list_1 [1, 2, 3, 4, 5] >>> list_1[:3] [1, 2, 3]
>>> tuple_1 (1, 2, 3, 4, 5) >>> tuple_1[2:] (3, 4, 5)
>>> string_1 '12345' >>> string_1[:] '12345'
>>> list_2 = list_1[:] >>> list_1 [1, 2, 3, 4, 5] >>> list_2 [1, 2, 3, 4, 5] >>> list_1[0] = 5 >>> list_1 [5, 2, 3, 4, 5] >>> list_2 [1, 2, 3, 4, 5]
in Operatorin is a boolean operator that can be used with sequencesin returns True if the sequence contains the value
VALUE in SEQUENCE
>>> nums = [1,2,3,4,5] >>> 3 in nums True >>> 6 in nums False >>> numbers = (1,2,3,4,5) >>> 2 in numbers True >>> 7 in numbers False >>> digits = "0123456789" >>> "2" in digits True >>> 'a' in digits False
in with strings you can search for more than 1 character
>>> digits = "0123456789" >>> "345" in digits True >>> "379" in digits False
| Method | Description |
|---|---|
| append(item) | Adds item to the end of the list |
| index(item) | Returns the index of the first element whose value is equal to item. A ValueError exception is raised if item is not found in the list. |
| insert(index, item) | Inserts item into the list at the specified index. When an item is inserted into a list, the list is expanded in size to accommodate the new item. The item that was previously at the specified index, and all the items after it, are shifted by one position toward 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) |
| remove(item) | Removes the first occurrence of item from the list. A ValueError exception is raised if item is not found in the list. |
| reverse() | Reverses the order of the items in the list |
del Statementdel
statement
del LIST_VARIABLE[INDEX]
>>> nums [1, 2, 3, 4, 5] >>> del nums[0] >>> nums [2, 3, 4, 5]
del statement with tuple or strings ...max will return the largest value in a sequence
>>> l1 = [1,2,3,4,5] >>> max(l1) 5
min will return the smallest
>>> min(l1) 1
>>> l2 = ["abacus", "bear", "cat", "dog"] >>> max(l2) 'dog' >>> min(l2) 'abacus'
>>> l3 = [1,2,4,"five"]
>>> max(l3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unorderable types: str() > int()
>>> nums_1 = [1,2,3,4,5] >>> nums_1[-1] 5 >>> nums_1[len(nums_1) -1] 5 >>> digits = "0123456789" >>> digits[-3] '7' >>> digits[len(digits) -3] '7'
>>> name ' Glenn ' >>> name.strip() 'Glenn' >>> team ' Red Sox' >>> team.strip() 'Red Sox'
>>> team 'Red Sox' >>> team.split() ["Red", "Sox"] >>> hamlet "To be\nor not to be" >>> hamlet.split() ["To", "be", "or", "not", "to", "be"]
>>> name "Glenn" >>> name.split() ["Glenn"]
>>> date1
"2016-05-03"
>>> date1.split("-")
["2016", "05", "03"]
>>> date2
"5/3/16"
>>> date2.split("/")
["5","3","16"]
>>> name.split("e")
["Gl", "nn"]
>>> name.split("n")
["Gle", ", "]
>>> date3
"5--3--16"
>>> date3.split("--")
["5", "3", "16"]