You need to enable JavaScript to run this app. Automate The Boring Stuff第3章之字形练习Python代码运行异常求助
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 00:12:00