# 享学课堂谈python中else的用途

from random import randrange

def insertion_sort(seq):

iflen(seq)1:

returnseq

_sorted=seq[:1]

foriinseq[1:]:

INSERTED=False

forjinrange(len(_sorted)):

ifi_sorted[j]:

_sorted=[*_sorted[:j],i,*_sorted[j:]]

INSERTED=True

break

ifnotinserted:

_sorted.append(i)

return_sorted

print(insertion_sort([randrange(1,100)foriinrange(10)]))

[8,12,12,34,38,68,72,78,84,90]

def insertion_sort(seq):

iflen(seq)1:

returnseq

_sorted=seq[:1]

foriinseq[1:]:

forjinrange(len(_sorted)):

ifi_sorted[j]:

_sorted=[*_sorted[:j],i,*_sorted[j:]]

break

else:

_sorted.append(i)

return_sorted

print(insertion_sort([randrange(1,100)foriinrange(10)]))

[1,10,27,32,32,43,50,55,80,94]

whileFalse:

print("Will never print!")

else:

print("Loop failed!")

Loop failed!

try...except...else...finally 流程控制语法用于捕捉可能出现的异常并进行相应的处理，其中 except 用于捕捉 try 语句中出现的错误；而 else 则用于处理没有出现错误的情况；finally 负责 try 语句的”善后工作“ ，无论如何都会执行。可以通过一个简单的例子来展示：

def divide(x,y):

try:

result=x/y

except ZeroDivisi:

print("division by 0!")

else:

print("result = {}".format(result))

finally:

print("divide finished!")

divide(5,2)

print("*"*20)

divide(5,0)

result=2.5

divide finished!

********************

division by0!

divide finished!

def divide(x,y):

result=None

try:

result=x/y

except ZeroDivisi:

print("division by 0!")

ifresult isnotNone:

print("result = {}".format(result))

print("divide finished!")

divide(5,2)

print("*"*20)

divide(5,0)

result=2.5

divide finished!

********************

division by0!

divide finished!

• 发表于:
• 原文链接：http://kuaibao.qq.com/s/20180103A06UUQ00?refer=cp_1026

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17

2019-02-17