翼度科技»论坛 编程开发 python 查看内容

7 错误及异常处理

8

主题

8

帖子

24

积分

新手上路

Rank: 1

积分
24
1.编写一个计算减法的方法,当第一个数小于第二个数时,抛出“被减数不能小于减数"的异常。
  1. class Sub(Exception):
  2.     def __init__(self, x, y):
  3.         self.x = x
  4.         self.y = y
  5. try:
  6.     a = int(input('请输入被减数'))
  7.     b = int(input('请输入减数'))
  8.     if a < b:
  9.         raise Sub(a, b)
  10. except Sub as error:
  11.     print('异常原因:被减数%d不能小于减数%d' % (error.x, error.y))
  12. else:
  13.     c = a - b
  14.     print('%d减%d的结果为%d' % (a, b, c))
  15. 输出结果:
  16. 请输入被减数>? 0
  17. 请输入减数>? 1
  18. 异常原因:被减数0不能小于减数1
  19. 请输入被减数>? 4
  20. 请输入减数>? 2
  21. 4减2的结果为2
复制代码
2.编写程序,提示输入两个数字a、b,并进行a与b的除法运算,把运算结果打印出来。要求对输入和程序进行检测,可以排除所有的错误。(可以使用以下的异常检查下面的错误:IOError、ValueError、ZeroDivisionError等,不能使用BaseException异常)。
  1. 方法一:
  2. def division() :
  3.     try :
  4.         a, b = int(input("输入两个数字以完成除法(a/b):"))
  5.         print("{} / {} = {}".format(a, b, c))
  6.     except ZeroDivisionError :
  7.         print("Error: The divisor can not be zero")  # 除数不能为零!
  8.     except IOError :
  9.         print("Error:Wrong input or output")  # 输入或输出错误”
  10.     except ValueError :
  11.         print("Error:Wrong value,变量应为数值类型!")  # 值错误
  12.     except NameError :
  13.         print("Error: No characters or strings 变量缺少")  # 使用了没有定义的对象,没有字符或字符串
  14.     except SyntaxError :
  15.         print("Error:No symbols or whitespaces")  # 语法错误:无符号或空格
  16.     except TypeError :
  17.         print("Error: The data type is wrong and must be number")  # 数据类型错误,必须要求除数和被除数是数字,不能是字符串或者其他
  18.     else :
  19.         print(a, '/', b, '=', c)<br><br><br>输出结果:
  20. 3/0
  21. Traceback (most recent call last):
  22.   File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
  23.     exec(code_obj, self.user_global_ns, self.user_ns)
  24.   File "<ipython-input-31-f6cc6d14333b>", line 1, in <module>
  25.     3/0
  26. ZeroDivisionError: division by zero
  27. 8/2
  28. Out[33]: 4.0
  29.     hhhhj/7
  30. NameError: name 'hhhhj' is not defined<br><br><br><br>方法二:
  31. try:
  32.     a = int(input("Please input the first number: "))
  33.     b = int(input("Please input the second number: "))
  34.     c = a / b
  35.     print("{} / {} = {}".format(a, b, c))
  36. except IOError:
  37.     print("You input a non-number!")
  38. except ValueError:
  39.     print("You input a non-number!")
  40. except ZeroDivisionError:
  41.     print("You can not divide a number by zero!")
  42. else:
  43.     print("Division done!")
  44. 输出结果:
  45. 请输入a的值:>? 3
  46. 请输入b的值:>? 2
  47. a除以b的结果是:1.5
  48. 请输入a的值:>? q
  49. 输入不是正确的数字,请重新输入:
  50. 请输入a的值:>? f
  51. 输入不是正确的数字,请重新输入:<br>
复制代码
3、定义函数,在控制台中获取成绩(1-100),如果输入有误,请重新输入。
  1. class OutOfRange(Exception) :
  2.     def __init__(self, x) :
  3.         self.x = x
  4.         self.x = "输入有误,请重新输入"
  5. def grades() :
  6.     try :
  7.         x = int(input("请输入[0,100]之间的分数:\n"))
  8.         if x < 0 or x > 100 :
  9.             raise OutOfRange(x)
  10.     except OutOfRange as er :
  11.         print(er.x)
  12.     else :
  13.         print("你的成绩为", x)
  14. grades()
  15. 输出结果:
  16. 100
  17. 你的成绩为 100
  18. -80
  19. 输入有误,请重新输入
  20. 120
  21. 输入有误,请重新输入
复制代码
  1. # 方法二:
  2. def score() :
  3.     global score
  4.     try :
  5.         score = int(input('请输入学生的成绩:'))
  6.         assert 0 <= score <= 100  # 断言 成绩必须在0-100范围内
  7.         if score >= 90 :
  8.             print("输入正确,成绩为:A ,优秀")
  9.         if 80 <= score < 90 :
  10.             print("输入正确,成绩为:B,良好")
  11.         if 60 <= score < 80 :
  12.             print("输入正确,成绩为:C,合格")
  13.         if score < 60 :
  14.             print("输入正确,成绩为:D,不及格")
  15.     except ValueError :
  16.         print("输入有误,输入必须为整数,请重新输入")
  17.     except AssertionError :  # 断言异常信息
  18.         print("输入有误,输入的成绩{},不在0-100范围内请重新输入,".format(score))
  19.     else :  # 可选项,必须try-except语句为前提
  20.         print("程序正常运行,没有捕捉到异常")
  21. score()
  22. <br>
  23. 输出结果:
  24. 请输入学生的成绩:>? 99
  25. 输入正确,成绩为:A ,优秀
  26. 程序正常运行,没有捕捉到异常
  27. 请输入学生的成绩:>? 55
  28. 输入正确,成绩为:D,不及格
  29. 程序正常运行,没有捕捉到异常
  30. 请输入学生的成绩:>? 66
  31. 输入正确,成绩为:C,合格
  32. 程序正常运行,没有捕捉到异常
  33. 请输入学生的成绩:>? -98
  34. 输入有误,输入的成绩-98,不在0-100范围内请重新输入,
复制代码
 
方法一:
  1. def division() :
  2.     try :
  3.         a, b = int(input("输入两个数字以完成除法(a/b):"))
  4.         print("{} / {} = {}".format(a, b, c))
  5.     except ZeroDivisionError :
  6.         print("Error: The divisor can not be zero")  # 除数不能为零!
  7.     except IOError :
  8.         print("Error:Wrong input or output")  # 输入或输出错误”
  9.     except ValueError :
  10.         print("Error:Wrong value,变量应为数值类型!")  # 值错误
  11.     except NameError :
  12.         print("Error: No characters or strings 变量缺少")  # 使用了没有定义的对象,没有字符或字符串
  13.     except SyntaxError :
  14.         print("Error:No symbols or whitespaces")  # 语法错误:无符号或空格
  15.     except TypeError :
  16.         print("Error: The data type is wrong and must be number")  # 数据类型错误,必须要求除数和被除数是数字,不能是字符串或者其他
  17.     else :
  18.         print(a, '/', b, '=', c)
复制代码
输出结果:
  1. 3/0
  2. Traceback (most recent call last):
  3.   File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
  4.     exec(code_obj, self.user_global_ns, self.user_ns)
  5.   File "<ipython-input-31-f6cc6d14333b>", line 1, in <module>
  6.     3/0
  7. ZeroDivisionError: division by zero
  8. 8/2
  9. Out[33]: 4.0
  10.     hhhhj/7
  11. NameError: name 'hhhhj' is not defined
复制代码
方法二:
  1. try:
  2.     a = int(input("Please input the first number: "))
  3.     b = int(input("Please input the second number: "))
  4.     c = a / b
  5.     print("{} / {} = {}".format(a, b, c))
  6. except IOError:
  7.     print("You input a non-number!")
  8. except ValueError:
  9.     print("You input a non-number!")
  10. except ZeroDivisionError:
  11.     print("You can not divide a number by zero!")
  12. else:
  13.     print("Division done!")
  14. 输出结果:
  15. 请输入a的值:>? 3
  16. 请输入b的值:>? 2
  17. a除以b的结果是:1.5
  18. 请输入a的值:>? q
  19. 输入不是正确的数字,请重新输入:
  20. 请输入a的值:>? f
  21. 输入不是正确的数字,请重新输入:
复制代码
来源:https://www.cnblogs.com/huangfeilonghfl/p/17092539.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!

举报 回复 使用道具