Day_10 · 异常处理:程序不崩溃的"安全网" #11
Reference in New Issue
Block a user
Delete Branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
今日知识点
try: ... except 异常类型: ...:把可能出错的代码放 try 里,出错就跳进 exceptValueError(值不对,如int("abc"))、ZeroDivisionError(除数为 0)先学(教程)
任务(后做)
新建
day10.py:123,一次输入abc,确认不崩溃且有提示。10 / 2、10 / 0、abc / 2三种情况。safe_int(s),能转就返回整数,不能转就返回None,再用它处理输入(
num = safe_int(input(...)),if num is None: 打印提示)。完成标准
int("abc")会抛什么异常提交方式:把
day10.py代码贴在当日工单评论里。参考解答(先做再看)
https://github.com/wyn-netizen/hello-daily-challenge
嗷
1
day10完成
10
1
`try:
num=int(input("输入一个数字:"))
print(f"你输入了{num}")
except ValueError:
print("你输的不是数字")
try:
a=int(input("被除数"))
b=int(input("除数"))
print(a/b)
except ValueError:
print("请输入数字")
except ZeroDivisionError:
print("除数不能为0!")`
10
-
1
。
Day_10 · 异常处理 try/except
输入 abc 被 ValueError 捕获、除数为 0 被 ZeroDivisionError 捕获,程序都没崩溃