Can while and else be used together in python

Introduction

Of course, it can be used together. This is one of the differences between python and other languages. Syntactic sugar makes the logic clearer.

example

# -*- 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()

result

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

refer to

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325813263&siteId=291194637