#!/usr/bin/env python # coding: utf-8 # # Biệt lệ (exception) và xác nhận (assertion) # # ## Biệt lệ # In[2]: 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') # In[ ]: 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.') print('Outside') # ## Ví dụ # In[ ]: while True: try: n = input('Please enter an integer:') n = int(n) break except ValueError: print('Input not an integer; try again') print('Correct input of an integer') # In[3]: 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) finally: fh.close() # close file even if fail # open file Files/testGradesData.py # In[4]: data # In[5]: 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) finally: fh.close() # close file even if fail gradesData = [] if data: for student in data: try: gradesData.append([student[0:2], [student[2]]]) except IndexError: gradesData.append([student[0:2], []]) # In[6]: gradesData # In[7]: 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) finally: fh.close() # close file even if fail gradesData = [] if data: for student in data: try: name = student[0:-1] grades = int(student[-1]) gradesData.append([name, [grades]]) except ValueError: gradesData.append([student[:], []]) # In[8]: gradesData # ## Phát sinh biệt lệ # In[9]: 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_ratios called with bad arg') return ratios # In[11]: L1 = [1, 2, 3, 4] L2 = [5, 6, 7, 8] get_ratios(L1, L2) # In[12]: L3 = [5, 6, 7] get_ratios(L1, L3) # In[14]: L4 = [5, 6, 7, 0] get_ratios(L1, L4) # In[20]: def get_stats(class_list): new_stats = [] for elt in class_list: new_stats.append([elt[0], elt[1], avg(elt[1])]) return new_stats #def avg(grades): # return sum(grades)/len(grades) #def avg(grades): # try: # return sum(grades)/len(grades) # except ZeroDivisionError: # print('no grades data') def avg(grades): try: return sum(grades)/len(grades) except ZeroDivisionError: print('no grades data') return 0.0 # In[21]: test_grades = [[['peter', 'parker'], [10.0, 5.0, 85.0]], [['bruce', 'wayne'], [10.0, 8.0, 74.0]], [['captain', 'america'], [8.0,10.0,96.0]], [['deadpool'], []]] get_stats(test_grades) # ## Assertion # In[25]: def avg(grades): assert not len(grades) == 0, 'no grades data' return sum(grades) / len(grades) # In[26]: avg([]) # - - - # [Trước: Kiểm thử chương trình](http://nbviewer.jupyter.org/github/manleviet/introCSusingPython/blob/master/7%20-%20Ki%E1%BB%83m%20th%E1%BB%AD%20ch%C6%B0%C6%A1ng%20tr%C3%ACnh.ipynb) | # [Mục lục](http://nbviewer.jupyter.org/github/manleviet/introCSusingPython/blob/master/index.ipynb) | # [Tiếp: Lập trình Hướng đối tượng](http://nbviewer.jupyter.org/github/manleviet/introCSusingPython/blob/master/9%20-%20L%E1%BA%ADp%20tr%C3%ACnh%20H%C6%B0%E1%BB%9Bng%20%C4%91%E1%BB%91i%20t%C6%B0%E1%BB%A3ng.ipynb)