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 divide(x, y):

try:

result = x / y

except ZeroDivisionError:

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 by 0!

divide finished!

def divide(x, y):

result = None

try:

result = x / y

except ZeroDivisionError:

print("division by 0!")

if result is not None:

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

print("divide finished!")

divide(5,2)

print("*"*20)

divide(5,0)

result = 2.5

divide finished!

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

division by 0!

divide finished!