如何检查命令是否已经执行

时间:2019-12-09 21:40:44

标签: python if-statement while-loop

问题出在这里:我不知道如何编写脚本,因此,如果我多次键入该脚本,则启动或停止脚本将显示“已运行”或“未运行”之类的内容

running = True
print("Type help for a list of commands. ")
while running :
    user=input("> ")
    user_input=user.upper()
    if user_input==("HELP"):
        print(f"""Type start to start the car.
Type stop to stop the car.
Type quit to quit the game.""")
    elif user_input==("START"):
        print("You started the car. ")
    elif user_input==("STOP"):
        print("You stopped the car. ")
    elif user_input==("QUIT"):
        print("You stopped the game.")
        running=False
    elif user_input!=("START") and user_input!=("STOP") and user_input!=("QUIT"):
        print("I don't understand that. ")

示例:

 >start
You started the car.
 >start
Car is already running.
 >stop
You stopped the car.
 >stop
Car isn't turned on.

1 个答案:

答案 0 :(得分:3)

首先,如果要停车,必须先启动,对吗?

制作一个全局变量(我们将其命名为started)并将其设置为False。 现在,当我们要“启动”汽车时,首先需要检查:

elif user_input==("START"):
    if started:
        print("Car is already running")
    else:
        print("You started the car")
        started = True

然后只需停止就执行类似的声明:如果startedTrue,则意味着您的汽车正在运行,您可以停止它。将started设置为False并显示汽车已停止的消息。否则,您甚至都没有打开汽车。

P.S。注意:在while循环之前声明并初始化started