python:else用法详解(简单、易懂含有样例解说)

在python中,else语句可以while和 for一起用
形式如下
While 条件 :
内容1
Else:
内容2
当while中内容1全部运行,才执行else中内容2,如果内容1中用break中途退出(或其他手段导致没有运行完),不执行else里的内容2
例子

num = int(input('请输入一个数:'))
while num > 0:
    x = num % 10
    print(x)
    num = num //10
    if(x == 0):
        print("里面有零")
        break
else:
    print("里面没零")

(小记:python中//代表返回整数)
在python中,else语句可以try一起用
Try:
内容1
Except 错误 变量:
内容2
Else:
内容3
当内容1没错时执行内容3,否则执行内容2

例子

try:
    int(123)
except ValueError as reason:
    print("出错了"+str(reason))
else:
    print("没有任何异常!")

发布了44 篇原创文章 · 获赞 4 · 访问量 1080

猜你喜欢

转载自blog.csdn.net/qq_44162236/article/details/102769490