import time, sys
num = 0 # *前需要显示多少个空格
numIncrease = True # 空格个数是否增加,True要增加
try:
while True: # 主函数体进行循环
print(' '*num,end='') # print后面跟的是空格不需要换行
print('*******')
time.sleep(0.1) # 程序停留0.1秒
if numIncrease:
# 空格个数需要增加
num = num + 1
if num == 10:
# 如果空格个数为10,那么开始空格个数减少
numIncrease = False
else:
# 空格个数需要减少
num = num - 1
if num == 0:
numIncrease = True
except KeyboardInterrupt:
sys.exit()
time包里调用了sleep函数,用来暂停,sys包里调用了exit函数,当使用者用键盘按下ctrl+c快捷键终止程序时,会引发KeyboardInterrupt异常,并由except语句处理,终止程序。实现的效果为:
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
*******
^C
Process finished with exit code 0