Automate The Boring Stuff第3章之字形练习Python代码运行异常求助
问题原因
你的代码存在两处核心错误:
- 控制缩进增减的逻辑块完全放在了
while True死循环的外层,while True默认不会主动终止,所以程序永远不会执行到修改indent和方向的代码,缩进值从始至终都停在初始值0。 - 逻辑分支缩进错误:
indentIncreasing为False时执行的缩进递减逻辑,错误地和if indent == 20分支对齐,而非和if indentIncreasing对齐,就算把逻辑移到循环内也会出现缩进值加1后立刻减1的问题,无法实现逐步移动的效果。
修正后完整代码
import time, sys indent = 0 # 缩进空格数 indentIncreasing = True # 缩进是否处于递增状态 try: while True: # 主程序循环 print(' ' * indent, end='') print('********') time.sleep(0.1) # 暂停0.1秒 if indentIncreasing: # 增加空格数 indent = indent + 1 if indent == 20: indentIncreasing = False else: # 减少空格数 indent = indent - 1 if indent == 0: indentIncreasing = True except KeyboardInterrupt: sys.exit()
效果对比
- 实际输出:

- 预期输出:

内容的提问来源于stack exchange,提问作者Koppány Lencsés
相关产品推荐
相关产品推荐

