送只羊抵油钱 发表于 2023-2-4 23:05:38

7 错误及异常处理

1.编写一个计算减法的方法,当第一个数小于第二个数时,抛出“被减数不能小于减数"的异常。

class Sub(Exception):
    def __init__(self, x, y):
      self.x = x
      self.y = y


try:
    a = int(input('请输入被减数'))
    b = int(input('请输入减数'))
    if a < b:
      raise Sub(a, b)
except Sub as error:
    print('异常原因:被减数%d不能小于减数%d' % (error.x, error.y))
else:
    c = a - b
    print('%d减%d的结果为%d' % (a, b, c))

输出结果:
请输入被减数>? 0
请输入减数>? 1
异常原因:被减数0不能小于减数1

请输入被减数>? 4
请输入减数>? 2
4减2的结果为22.编写程序,提示输入两个数字a、b,并进行a与b的除法运算,把运算结果打印出来。要求对输入和程序进行检测,可以排除所有的错误。(可以使用以下的异常检查下面的错误:IOError、ValueError、ZeroDivisionError等,不能使用BaseException异常)。

方法一:
def division() :
    try :
      a, b = int(input("输入两个数字以完成除法(a/b):"))
      print("{} / {} = {}".format(a, b, c))

    except ZeroDivisionError :
      print("Error: The divisor can not be zero")# 除数不能为零!
    except IOError :
      print("Error:Wrong input or output")# 输入或输出错误”
    except ValueError :
      print("Error:Wrong value,变量应为数值类型!")# 值错误
    except NameError :
      print("Error: No characters or strings 变量缺少")# 使用了没有定义的对象,没有字符或字符串
    except SyntaxError :
      print("Error:No symbols or whitespaces")# 语法错误:无符号或空格
    except TypeError :
      print("Error: The data type is wrong and must be number")# 数据类型错误,必须要求除数和被除数是数字,不能是字符串或者其他
    else :
      print(a, '/', b, '=', c)<br><br><br>输出结果:
3/0
Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-31-f6cc6d14333b>", line 1, in <module>
    3/0
ZeroDivisionError: division by zero

8/2
Out: 4.0

    hhhhj/7
NameError: name 'hhhhj' is not defined<br><br><br><br>方法二:
try:
    a = int(input("Please input the first number: "))
    b = int(input("Please input the second number: "))
    c = a / b
    print("{} / {} = {}".format(a, b, c))
except IOError:
    print("You input a non-number!")
except ValueError:
    print("You input a non-number!")
except ZeroDivisionError:
    print("You can not divide a number by zero!")
else:
    print("Division done!")

输出结果:
请输入a的值:>? 3
请输入b的值:>? 2
a除以b的结果是:1.5

请输入a的值:>? q
输入不是正确的数字,请重新输入:
请输入a的值:>? f
输入不是正确的数字,请重新输入:<br>3、定义函数,在控制台中获取成绩(1-100),如果输入有误,请重新输入。

class OutOfRange(Exception) :
    def __init__(self, x) :
      self.x = x
      self.x = "输入有误,请重新输入"


def grades() :
    try :
      x = int(input("请输入之间的分数:\n"))
      if x < 0 or x > 100 :
            raise OutOfRange(x)
    except OutOfRange as er :
      print(er.x)
    else :
      print("你的成绩为", x)


grades()

输出结果:
100
你的成绩为 100
-80
输入有误,请重新输入
120
输入有误,请重新输入# 方法二:
def score() :
    global score
    try :

      score = int(input('请输入学生的成绩:'))
      assert 0 <= score <= 100# 断言 成绩必须在0-100范围内
      if score >= 90 :
            print("输入正确,成绩为:A ,优秀")
      if 80 <= score < 90 :
            print("输入正确,成绩为:B,良好")
      if 60 <= score < 80 :
            print("输入正确,成绩为:C,合格")
      if score < 60 :
            print("输入正确,成绩为:D,不及格")
    except ValueError :
      print("输入有误,输入必须为整数,请重新输入")
    except AssertionError :# 断言异常信息
      print("输入有误,输入的成绩{},不在0-100范围内请重新输入,".format(score))
    else :# 可选项,必须try-except语句为前提
      print("程序正常运行,没有捕捉到异常")


score()
<br>
输出结果:

请输入学生的成绩:>? 99
输入正确,成绩为:A ,优秀
程序正常运行,没有捕捉到异常

请输入学生的成绩:>? 55
输入正确,成绩为:D,不及格
程序正常运行,没有捕捉到异常

请输入学生的成绩:>? 66
输入正确,成绩为:C,合格
程序正常运行,没有捕捉到异常

请输入学生的成绩:>? -98
输入有误,输入的成绩-98,不在0-100范围内请重新输入, 
方法一:
def division() :
    try :
      a, b = int(input("输入两个数字以完成除法(a/b):"))
      print("{} / {} = {}".format(a, b, c))

    except ZeroDivisionError :
      print("Error: The divisor can not be zero")# 除数不能为零!
    except IOError :
      print("Error:Wrong input or output")# 输入或输出错误”
    except ValueError :
      print("Error:Wrong value,变量应为数值类型!")# 值错误
    except NameError :
      print("Error: No characters or strings 变量缺少")# 使用了没有定义的对象,没有字符或字符串
    except SyntaxError :
      print("Error:No symbols or whitespaces")# 语法错误:无符号或空格
    except TypeError :
      print("Error: The data type is wrong and must be number")# 数据类型错误,必须要求除数和被除数是数字,不能是字符串或者其他
    else :
      print(a, '/', b, '=', c)输出结果:
3/0
Traceback (most recent call last):
File "D:\Anaconda\lib\site-packages\IPython\core\interactiveshell.py", line 2963, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-31-f6cc6d14333b>", line 1, in <module>
    3/0
ZeroDivisionError: division by zero

8/2
Out: 4.0

    hhhhj/7
NameError: name 'hhhhj' is not defined方法二:
try:
    a = int(input("Please input the first number: "))
    b = int(input("Please input the second number: "))
    c = a / b
    print("{} / {} = {}".format(a, b, c))
except IOError:
    print("You input a non-number!")
except ValueError:
    print("You input a non-number!")
except ZeroDivisionError:
    print("You can not divide a number by zero!")
else:
    print("Division done!")

输出结果:
请输入a的值:>? 3
请输入b的值:>? 2
a除以b的结果是:1.5

请输入a的值:>? q
输入不是正确的数字,请重新输入:
请输入a的值:>? f
输入不是正确的数字,请重新输入:
来源:https://www.cnblogs.com/huangfeilonghfl/p/17092539.html
免责声明:由于采集信息均来自互联网,如果侵犯了您的权益,请联系我们【E-Mail:cb@itdo.tech】 我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: 7 错误及异常处理