python中的else的详细介绍

from random import randrange
def insertion_sort(seq):
if len(seq) 1:
return seq
_sorted = seq[:1]
for i in seq[1:]:
inserted = false
for j in range(len(_sorted)):
if i _sorted[j]:
_sorted = [*_sorted[:j], i, *_sorted[j:]]
inserted = true
break
if not inserted:
_sorted.append(i)
return _sorted
print(insertion_sort([randrange(1, 100) for i in range(10)]))
[8, 12, 12, 34, 38, 68, 72, 78, 84, 90]

def insertion_sort(seq):
if len(seq) 1:
return seq
_sorted = seq[:1]
for i in seq[1:]:
for j in range(len(_sorted)):
if i _sorted[j]:
_sorted = [*_sorted[:j], i, *_sorted[j:]]
break
else:
_sorted.append(i)
return _sorted
print(insertion_sort([randrange(1, 100) for i in range(10)]))
[1, 10, 27, 32, 32, 43, 50, 55, 80, 94]

while false:
print(“will never print!”)
else:
print(“loop failed!”)
loop failed!

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

def pide(x, y):
try:
result = x / y
except zeropisionerror:
print(“pision by 0!”)
else:
print(“result = {}”.format(result))
finally:
print(“pide finished!”)
pide(5,2)
print(“*”*20)
pide(5,0)

result = 2.5
pide finished!
********************
pision by 0!
pide finished!

def pide(x, y):
result = none
try:
result = x / y
except zeropisionerror:
print(“pision by 0!”)
if result is not none:
print(“result = {}”.format(result))
print(“pide finished!”)
pide(5,2)
print(“*”*20)
pide(5,0)

result = 2.5
pide finished!
********************
pision by 0!
pide finished!

Posted in 未分类