ages = [35, 35, 23, 18, 45, 18, 72]
try:
print(ages[0] + ages[4])
except:
print('Failed to print the sum of two ages')
80
try:
and except:
try:
and except:
try:
and except:
ages = [35, 35, 23, 18, 45, 18, 72]
try:
print(ages[0] + ages[7])
except:
print('Failed to print the sum of two ages')
print('Tried to get a value from an index that does not exist in the list')
Failed to print the sum of two ages
Tried to get a value from an index that does not exist in the list
IndexError: list index out of range
Write a python function called valid_input
that takes a string as argument and returns False if the string is not a year (check if the length is 4, and if the string is an integer).
Name your file year_validation.py
read_numbers
def read_numbers(file_name):
floats = []
not_floats = []
f = open(file_name, "r")
for line in f:
words = line.strip().split(" ")
for w in words:
try:
floats.append(float(w))
except:
not_floats.append(w)
f.close()
return floats
def main():
print( read_numbers("weather.txt") ) # [89.5, 50.2, 93.4, 69.0]
main()
[89.5, 50.2, 93.4, 69.0]
def read_numbers(file_name):
floats = []
not_floats = []
f = open(file_name, "r")
for line in f:
words = line.strip().split(" ")
for w in words:
try:
floats.append(float(w))
except Exception as err:
not_floats.append(w)
print(err)
else:
print("coverted", w, "successfully")
f.close()
return floats
def main():
print( read_numbers("weather.txt") ) # [89.5, 50.2, 93.4, 69.0]
main()
could not convert string to float: 'Tucson'
could not convert string to float: '--'
could not convert string to float: 'high'
could not convert string to float: 'temperature:'
coverted 89.5 successfully
could not convert string to float: 'Tucson'
could not convert string to float: '--'
could not convert string to float: 'low'
could not convert string to float: 'temperature:'
coverted 50.2 successfully
could not convert string to float: 'Phoenix'
could not convert string to float: '--'
could not convert string to float: 'high'
could not convert string to float: 'temperature:'
coverted 93.4 successfully
could not convert string to float: 'Phoenix'
could not convert string to float: '--'
could not convert string to float: 'low'
could not convert string to float: 'temperature:'
coverted 69.0 successfully
[89.5, 50.2, 93.4, 69.0]