【问题标题】:Automate The Boring Stuff Chapter 3: Zig-Zag exercise自动化无聊的东西第 3 章:之字形练习
【发布时间】:2021-07-29 08:43:42
【问题描述】:

我很难弄清楚为什么我的代码不能按预期工作。 我的输出看起来像一堆星号,而不是正确的之字形。

import time, sys

indent = 0 # How many spaces to indent.
indentIncreasing = True #Whether or not the indent increases

try:
    while True:
        #The main program loop
        print(' ' * indent, end='')
        print('********')
        time.sleep(0.1) # Pause for 1/10 of a second.
    
    if indentIncreasing:
        
        #Increase the number of spaces:
        indent = indent + 1
        if indent == 20:
            indentIncreasing = False
       # Change direction:
        else:
            #decrease the number of spaces:
            indent = indent - 1
            if indent == 0:
                #Change direction:
                indentIncreasing = True
except KeyboardInterrupt:
    sys.exit() 

我的输出:

期望的输出:

【问题讨论】:

  • 您能否包括所需的行为和当前输出?
  • 是的,我在一些链接中发布了它,希望它足够好,因为这是我的第一篇文章。 :D
  • 说到缩进,我认为你需要缩进从if indentIncreasing:开始到else的代码块。
  • 现在,if 语句在 while 循环之外,所以 indent 永远不会改变。

标签: python output


【解决方案1】:

您使用的while 循环是一个无限循环(因为它没有更新或跳转语句)。
一个合适的while 循环应该有以下四个:

  1. 控制变量的初始化,
  2. while循环的测试语句,
  3. 循环体,以及
  4. 控制变量的更新。

编辑您的代码,使 while 循环不是无限循环。

希望这可以帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-10-09
    • 1970-01-01
    • 2016-04-01
    相关资源
    最近更新 更多