语言程序错误
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:
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、逻辑错误
程序跑出来了,但结果是错的,就是逻辑错误啦!