python3
python3
You should read Chapter 7, Lists and Tuples, from our textbook, Starting Out with Python, before next week's class.
I have posted homework 9 here.
It is due this coming Sunday at 11:59 PM.
You must make the script for this assignment executable or you will loose points
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
2017-06-01 67 2017-06-02 71 2017-06-03 69 ...
>>> line = '2017-06-01 67' date, temp = line.split()
2017-06-01 67 2017-06-02 71 2017-06-03 69 2017-06-04 88 2017-06-05 74 ...
count = 0 total = 0 for line in file: count += 1 date, temp = line.split() temp = int(temp) total += temp average = roung(total/count)
file.close()
2017-06-01 67 2017-06-02 71 2017-06-03 69 ...
set a variable to a value that will be replaced
for each value
if the value is greater than the variable
give the variable the new value
max_date = '' min_date = ''
if temp > max: max = temp max_date = date if temp < min: min = temp min_date = date
#! /usr/bin/python3 file = open('temps.txt', 'r') max = -100 min = 200 max_date = '' min_date = '' for line in file: date, temp = line.split() temp = int(temp) if temp > max: max = temp max_date = date if temp < min: min = temp min_date = date print('Maximum:', max_date, max) print('Minimum:', min_date, min)
$ ./temps_max_min_dates.py Maximum: 2017-06-24 89 Minimum: 2017-06-26 66
>>> 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
$ cat get_number_1.py
#! /usr/bin/python3
number = int(input("Number: ")
$ ./get_number_1.py
File "./get_number_1.py", line 6
^
SyntaxError: unexpected EOF while parsing
>>> for i in range(5):
... num = i * 2
... print(num)
File "<stdin>", line 3
print(num)
^
IndentationError: unindent does not match any outer indentation level
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'
$ ./int_request.py
Integer: five
Traceback (most recent call last):
File "./int_request.py", line 5, in <module>
number = int(input("Integer: "))
ValueError: invalid literal for int() with base 10: 'five'
>>> round("five")
Traceback (most recent call last):
File "<stdin>, line 1, in <module>
TypeError: type str doesn't define __round__ method
$ ./divide_two_numbers.py
Numerator: 5
Denominator: 0
Traceback (most recent call last):
File "./divide_two_numbers.py", line 7, in <module>
result = numerator / denominator
ZeroDivisionError: division by zero
Segmentation fault: Core dumped
try
/except
statement which has the following form
try:
STATEMENT
STATEMENT
...
except:
STATEMENT
STATEMENT
...
try
code block
execute normally unless a runtime error occurs
try
blockexcept
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
looptry
codeinput
function to ask the user for an integer
>>> number = int(input("Integer: "))
Integer: 5.0
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '5.0'
while
loop
ask the user for a value
while the value is not valid:
print an error message
ask the user for a value
return the value
try
/except
statementtry
/except
statement needs to be inside the loopwhile
loop use?False
while
loop will keep running as long as the flag is False
True
set a flag to false
while the flag is not true
ask the user for a value
try:
convert the value to an integer
set the flag to true
except:
print an error message
return the value
def get_integer(): done = False while not done: number = input("Integer: ") try: number = int(number) done = True except: print(number, 'cannot be converted into an integer') return number
$ ./get_integer.py Integer: 2.0 2.0 cannot be converted into an integer Integer: 2 2
while
loop runs when we don't yet have a valuewhile True
return
statementreturn
statement will be runreturn
statement always causes the function to stopdef get_integer(): while True: number = input("Integer: ") try: number = int(number) return number except: print(number, 'cannot be converted into an integer')