You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python while循环实现简易汽车游戏 修复重复启停逻辑问题

功能需求
  • 输入help指令时输出以下提示:
start-to start the car
stop-to stop the car
quit-to exit
  • 输入start指令时输出提示:Car started
  • 输入stop指令时输出提示:Car stopped
  • 输入quit指令时终止程序循环
  • 增加重复操作拦截:重复执行start需提示car started already;重复执行stop需提示car stopped already
现有基础代码

当前已实现基础指令响应,但缺少车辆状态校验逻辑,无法拦截重复启停操作,代码如下:

command=""
while True:
    command=input('>').lower()
    if command=='start':
        print("Car started")
    elif command=='stop':
         print("Car stopped")
    elif command=="help":
        print('''
start-to start the car
stop-to stop the car
quit-to exit
        ''')
    elif command=='quit':
        break
    else:
        print("I don't understand that")
实现方案

核心逻辑是新增布尔变量标记车辆实时启停状态,每次执行启停指令前先做状态校验,仅当状态匹配操作要求时才执行指令、更新状态,否则输出重复操作提示。
具体修改点:

  • 循环外初始化状态变量is_started = False,默认车辆为熄火状态
  • start指令分支先判断当前状态:如果车辆已启动,直接输出重复启动提示;未启动则输出启动成功提示,同时将状态标记为已启动
  • stop指令分支先判断当前状态:如果车辆已熄火,直接输出重复熄火提示;未熄火则输出熄火成功提示,同时将状态标记为已熄火
  • 其余指令分支逻辑保持原有实现不变

修改完成的可运行完整代码:

command = ""
# 标记车辆启停状态:False=熄火,True=已启动
is_started = False
while True:
    command = input('>').lower()
    if command == 'start':
        if is_started:
            print("car started already")
        else:
            print("Car started")
            is_started = True
    elif command == 'stop':
        if not is_started:
            print("car stopped already")
        else:
            print("Car stopped")
            is_started = False
    elif command == "help":
        print('''
start-to start the car
stop-to stop the car
quit-to exit
        ''')
    elif command == 'quit':
        break
    else:
        print("I don't understand that")

内容的提问来源于stack exchange,提问作者Yanji Lama

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 08:12:25