简体   繁体   中英

How can I get “START!” to print after the first line of asterisks when I run it, rather than just the changes of direction?

It will print start and stop, but not on the first line? How can I get "START," to print after the first line of asterisks when I run it? rather than just the changes of direction?

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 + " STOP!")
                indentIncreasing = False

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

except KeyboardInterrupt:
    sys.exit()

How about just adding a print statement before the while loop and initializing indent at 1 instead of 0?

indent = 1
indentIncreasing = True

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

Check for the start/stop conditions first.

I've used a variable to hold the START and STOP messages, then I can leave it blank for the other lines. This allows a single print() line for all cases.

stars = "*" * userInput

indent = -1
indentIncreasing = True

try:
    while True:
        startstop = ''
        if indentIncreasing:
            indent = indent + 1
            if indent == 20:
                startstop = ' STOP!'
                indentIncreasing = False
        else:
            indent = indent - 1
            if indent == 0:
                startstop = ' START!'
                indentIncreasing = True

        print(' ' * indent + stars + startstop)
        time.sleep(0.1)

except KeyboardInterrupt:
    sys.exit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM