异常错误代码什么意思(7 错误及异常处理)
导读:方法一: def division( : try : a, b = int(input("输入两个数字以完成除法(a/b :" prin...
方法一:
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[33]: 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 输入不是正确的数字 ,请重新输入:
声明:本站所有文章 ,如无特殊说明或标注 ,均为本站原创发布 。任何个人或组织 ,在未征得本站同意时 ,禁止复制 、盗用 、采集、发布本站内容到任何网站 、书籍等各类媒体平台 。如若本站内容侵犯了原著者的合法权益 ,可联系我们进行处理。
创心域SEO版权声明:以上内容作者已申请原创保护,未经允许不得转载,侵权必究!授权事宜、对本内容有异议或投诉,敬请联系网站管理员,我们将尽快回复您,谢谢合作!