python 中while能和else一起使用么

时间:2022-12-13 11:41:57

简介

当然可以一起用了,这个是python和其他语言不一样的地方之一,语法糖糖,让逻辑更加清晰

例子

# -*- coding:utf-8 -*-

__author__ = 'ink'
__date__ = '2018/3/20 23:48'


def suger():
    value = True
    if value is True:
        print('value is True')
    else:
        print('value is False')

    for idx in range(1, 5):
        print('idx {0}'.format(idx))
    else:
        print('exit for loop')

    num = 30
    while num > 20:
        num = num - 1

    else:
        print('exit while loop')

    try:
        with open("data.txt") as file:
            data = file.readlines()
    except Exception:
        print('open failed')
    else:
        print('open succeed')


suger()

结果

value is True
idx  1
idx  2
idx  3
idx  4
exit for loop
exit while loop
open failed

参考

http://www.runoob.com/python/python-exceptions.html