【python⼆级】错误及错误处理
语⾔程序错误
1、语法错误
2、运⾏错误
运⾏过中程序意外终⽌的错误,最常见的有1/0
1/0
---------------------------------------------------------------------------
ZeroDivisionError                        Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_12736/2354412189.py in <module>
----> 1 1/0
ZeroDivisionError: division by zero
避免运⾏错误
为了避免因为出现运⾏错误,⽽导致的整个程序瘫痪,可以使⽤try-except-else 代码块。
try代码块中只包含可能出现错误的代码,except代码块表⽰出现错误(ZeroDivisionError、FileNotFoundError等)时要怎么办,else 代码块只运⾏try代码块可以运⾏成功的代码。
还是以0做除数为例,创建⼀个只执⾏除法运算的简单计算器:
x =input("input the first number:")
y =input("input the second number")
try:
z=int(x)/int(y)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(z)
还可以加⼊while语句,实现连续输⼊
while True:
x =input("input the first number:")
y =input("input the second number")
try:
python新手代码错了应该怎么改z=int(x)/int(y)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print(z)
静默错误
有时候你希望程序在发⽣异常时保持静默,就像什么都没有发⽣⼀样继续运⾏,只需要在except语句中输⼊pass就可以了!
while True:
x =input("input the first number:")
y =input("input the second number")
try:
z=int(x)/int(y)
except ZeroDivisionError:
pass
else:
print(z)
3、逻辑错误
程序跑出来了,但结果是错的,就是逻辑错误啦!