1、类似于try-except,但是如果程序没有错误,即没有跳到except语句块,则执行else语句块。
2、如果程序出现错误,即跳到except语句块,则直接跳过else语句块。
try: <语句>#运行别的代码 except<名字>: <语句>#如果在try部份引发了'name'异常 except<名字>,<数据>: <语句>#如果引发了'name'异常,获得附加的数据 else: <语句>#如果没有异常发生
实例
defdivision(DivideBy): return42/DivideBy try: num=int(input("Pleaseinputainteger:\n")) print(division(num)) exceptZeroDivisionError:#except后写错误类型 print("Dividedbyzero!") exceptValueError: print("Wronginput!") else: print("Noerror.Goodjob!")
以上就是python中try-except-else语句的介绍,希望对大家有所帮助。
本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。