欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python異常中else的實(shí)例用法

 更新時(shí)間:2021年06月15日 08:41:54   作者:小妮淺淺  
在本篇內(nèi)容里小編給大家分享的是一篇關(guān)于python異常中else的實(shí)例用法,有興趣的朋友們可以跟著學(xué)習(xí)下。

1、說明

當(dāng)確定沒有異常后,還需要做一些事情可以使用else語(yǔ)句。

注意:try中沒有異常,else之后的代碼才會(huì)被執(zhí)行。

2、實(shí)例

while True:
    try:
        x = int(input('請(qǐng)輸入X:'))
        y = int(input('請(qǐng)輸入Y:'))
        value = x / y
        print('x/y is',value)
    except Exception as e:  # 發(fā)生異常時(shí)執(zhí)行
        print('不正確的輸入:', e)
        print('請(qǐng)重新輸入')
    else:  # 未發(fā)生異常時(shí)執(zhí)行
        break

實(shí)例擴(kuò)展:

def fetcher(obj, index):
    return obj[index]
 
x = 'spam'
 
try:
    print fetcher(x, 3)
except Exception:
    print 'hhh'
else:
    print 'has no exception'
    print fetcher(x, 2)
    print '---' * 10
 
try:
    print fetcher(x, 4)
except IndexError:
    print 'got exception'
else:
    print 'has no exception'
    print fetcher(x, 2)

運(yùn)行結(jié)果:

m
has no exception
a
------------------------------
got exception

到此這篇關(guān)于python異常中else的實(shí)例用法的文章就介紹到這了,更多相關(guān)python異常中else的使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論