脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python异常中else的实例用法

python异常中else的实例用法

2021-12-01 10:14小妮浅浅 Python

在本篇内容里小编给大家分享的是一篇关于python异常中else的实例用法,有兴趣的朋友们可以跟着学习下。

1、说明

当确定没有异常后,还需要做一些事情可以使用else语句。

注意:try中没有异常,else之后的代码才会被执行。

2、实例

?
1
2
3
4
5
6
7
8
9
10
11
while True:
    try:
        x = int(input('请输入X:'))
        y = int(input('请输入Y:'))
        value = x / y
        print('x/y is',value)
    except Exception as e:  # 发生异常时执行
        print('不正确的输入:', e)
        print('请重新输入')
    else# 未发生异常时执行
        break

实例扩展:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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)

运行结果:

?
1
2
3
4
5
m
has no exception
a
------------------------------
got exception

到此这篇关于python异常中else的实例用法的文章就介绍到这了,更多相关python异常中else的使用内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.py.cn/jishu/jichu/30982.html

延伸 · 阅读

精彩推荐