Common error types:
fail silently:
return an “error” value
stop execution, signal error condition
Python code can provide handlers for exceptions
try:
a = int(input("Tell me one number:"))
b = int(input("Tell me another number:"))
print(a/b)
print ("Okay")
except:
print("Bug in user input.")
print("Outside")
try:
a = int(input("Tell me one number:"))
b = int(input("Tell me another number:"))
print(a/b)
print ("Okay")
except:
print("Bug in user input.")
print("Outside")
Have separate exceptclauses to deal with a particular type of exception
try:
a = int(input("Tell me one number: "))
b = int(input("Tell me another number: "))
print("a/b = ", a/b)
print("a+b= ", a+b)
except ValueError:
print("Could not convert to a number.")
except ZeroDivisionError:
print("Can't divide by zero")
except:
print("Something went very wrong.")
try:
a = int(input("Tell me one number: "))
b = int(input("Tell me another number: "))
print("a/b = ", a/b)
print("a+b= ", a+b)
except ValueError:
print("Could not convert to a number.")
except ZeroDivisionError:
print("Can't divide by zero")
except:
print("Something went very wrong.")
else:
finally:
data = []
file_name= input("Provide a name of a file of data ")
try:
fh = open(file_name, 'r')
except IOError:
print('cannot open', file_name)
else:
for new in fh:
if new != '\n':
addIt= new[:-1].split(',') #remove trailing \n
data.append(addIt)
fh.close() # close file even if fail
finally:
print("End of the code") # always exicuted
#seperate grades and name
L = [['John','Don','56'],['Von','Neouman'],['Mr','Godfather','Corlinone','99']]
gradesData= []
for student in L:
print(student)
try:
name = student[0:-1]
grades = int(student[-1])
gradesData.append([name, [grades]])
except ValueError: # if ValueError i.e could not convert string into int in line 9
gradesData.append([student[:], []])
print(gradesData)
example
def get_ratios(L1, L2):
""" Assumes: L1 and L2 are lists of equal length of numbers
Returns: a list containing L1[i]/L2[i] """
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(L2[index]))
except ZeroDivisionError:
ratios.append(float('NaN')) #NaN= Not a Number
except:
raise ValueError('get_ratioscalled with bad arg') # error that we want to be raised
return ratios
L1 = [1,2,3]
L2 = [0,5,8]
get_ratios(L1, L2)
def get_ratios(L1, L2):
""" Assumes: L1 and L2 are lists of equal length of numbers
Returns: a list containing L1[i]/L2[i] """
ratios = []
for index in range(len(L1)):
try:
ratios.append(L1[index]/float(L2[index]))
except ZeroDivisionError:
ratios.append(float('NaN')) #NaN= Not a Number
except:
raise ValueError('get_ratioscalled with bad arg') # error that we want to be raised
return ratios
L1 = [1,2,3,4]
L2 = [0,5,8]
get_ratios(L1, L2)
Makes sure the contions required are meet before even computation.
#example
def normalize(numbers):
max_number = max(numbers)
assert(max_number != 0), "Cannot divide by 0" #making sure max is not 0
for i in range(len(numbers)):
numbers[i] /= float(max_number)
assert(0.0 <= numbers[i] <= 1.0), "output not between 0 and 1"
return numbers
numbers = [1,2,3]
normalize(numbers)
#example
def normalize(numbers):
max_number = max(numbers)
assert(max_number != 0), "Cannot divide by 0"
for i in range(len(numbers)):
numbers[i] /= float(max_number)
assert(0.0 <= numbers[i] <= 1.0), "output not between 0 and 1"
return numbers
numbers = [0,0,0] # should throw an error
normalize(numbers)
HAND_SIZE = 7
SCRABBLE_LETTER_VALUES = {
'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10
}
def getWordScore(word, n):
"""
Returns the score for a word. Assumes the word is a valid word.
The score for a word is the sum of the points for letters in the
word, multiplied by the length of the word, PLUS 50 points if all n
letters are used on the first turn.
Letters are scored as in Scrabble; A is worth 1, B is worth 3, C is
worth 3, D is worth 2, E is worth 1, and so on (see SCRABBLE_LETTER_VALUES)
word: string (lowercase letters)
n: integer (HAND_SIZE; i.e., hand size required for additional points)
returns: int >= 0
"""
score = 0
for i in word:
score += SCRABBLE_LETTER_VALUES[i]
score *= len(word)
if len(word) == n:
score += 50
return score
getWordScore("hello", 5)
def updateHand(hand, word):
"""
Assumes that 'hand' has all the letters in word.
In other words, this assumes that however many times
a letter appears in 'word', 'hand' has at least as
many of that letter in it.
Updates the hand: uses up the letters in the given word
and returns the new hand, without those letters in it.
Has no side effects: does not modify hand.
word: string
hand: dictionary (string -> int)
returns: dictionary (string -> int)
"""
update = hand.copy()
for x in word:
update[x] = update.get(x,0) - 1
return update
word = 'quail'
hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
updateHand(hand, 'quail')
def isValidWord(word, hand, wordList):
"""
Returns True if word is in the wordList and is entirely
composed of letters in the hand. Otherwise, returns False.
Does not mutate hand or wordList.
word: string
hand: dictionary (string -> int)
wordList: list of lowercase strings
"""
# TO DO ... <-- Remove this comment when you code this function
flag = 0
D = hand.copy()
for x in word:
if D.get(x,0) != 0:
D[x] = D.get(x,0) - 1
else:
flag = 1
if flag == 0:
if word in wordList:
return True
return False
word = 'quail'
hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':1}
wordList = ['quail','hello']
isValidWord(word, hand, wordList)
hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':0}
handlen = 0
for i in hand:
handlen += hand[i]
handlen
input("Print x: ")
def displayHand(hand):
"""
Displays the letters currently in the hand.
For example:
>>> displayHand({'a':1, 'x':2, 'l':3, 'e':1})
Should print out something like:
a x x l l l e
The order of the letters is unimportant.
hand: dictionary (string -> int)
"""
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print()
hand = {'a':1, 'q':1, 'l':2, 'm':1, 'u':1, 'i':0}
displayHand(hand)
print("Current Hand: ",end='')
displayHand(hand)
str(displayHand(hand))
letter = input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ")
letter
print('Hello', end = " ")
print('world', end="?")
print('!')
Reference