首页 > 解决方案 > 如何让星号来回打印开始和停止?

问题描述

我已经尝试了我在这个项目上能找到的一切,以在我的教授指导下完成它。我无法弄清楚如何简单有效地让星号左右移动,然后“开始!” 和“停止!” 关于方向的改变。非常感谢任何注释或帮助理解。这是我到目前为止所拥有的。

import time, sys

while True:
    try:
        print("Enter and integer between 5 and 15: ")
        userInput = int(input())
        if userInput < 5 or userInput > 15:
            continue
    else:
        break
except ValueError:
    print("You must enter an integer.")
    continue

stars = ''

indent = 0
indentIncreasing = True


try:
    stars += "*" * userInput
    while True:
        print('' * indent, end='')
        print(stars)
        time.sleep(0.1)

    if indentIncreasing:
        indent = indent + 1
        if indent == 20:
            print('' * 20 + stars + " START!")
            indentIncreasing = False

    else:
        indent = indent - 1
        if indent == 0:
            print(stars + " STOP!")
            indentIncreasing = True

except KeyboardInterrupt:
    sys.exit()

感谢你们!

标签: python

解决方案


您的函数在第二个 while 循环中缺少缩进以包含 if 语句。当您将它们相乘时,'' 之间也缺少一个空格。我还修复了奇怪的 try 语句。尝试:

import time, sys

while True:
    try:
        print("Enter and integer between 5 and 15: ")
        userInput = int(input())
        if userInput < 5 or userInput > 15:
            continue
        break
    except ValueError:
        print("You must enter an integer.")
        

stars = ''

indent = 0
indentIncreasing = True


try:
    stars += "*" * userInput
    while True:
        print(' ' * indent, end='')  # Added a space between the first ''
        print(stars)
        time.sleep(0.1)

        # Indented the following if and else statements
        if indentIncreasing: 
            indent = indent + 1
            if indent == 20:
                print(' ' * 20 + stars + " START!") # Added a space between the ''
                indentIncreasing = False
 
        else:
            indent = indent - 1
            if indent == 0:
                print(stars + " STOP!")
                indentIncreasing = True

except KeyboardInterrupt:
    sys.exit(

推荐阅读