1——当我们输入帮助时应该出现以下内容:
启动汽车停车——停车quit退出
2—当我们输入启动消息时:汽车启动应显示
3——当输入stop时:应显示汽车已停
4—当输入quit…应该通过循环
退出5——我们不能启动汽车两次或两次以上——像汽车已经启动这样的信息应该和停止一样显示我的代码:
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_car_started
来记录汽车是否已经启动的状态。启动汽车时,将is_car_started
设置为True。当你停车时,把它设为false。
command=""
is_car_started = False
while True:
command=input('>').lower()
if command=='start':
if is_car_started == True:
print("Car started already")
else:
is_car_started = True
print("Car started")
elif command=='stop':
is_car_started = False
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")
你可以在while循环之外定义一个布尔变量。如first_start = true
然后在if语句的while循环中检查command=="start"
,您可以将first_start
设置为false。
在最上面,你可以添加一个if语句,当first_start == false
.
if语句看起来像这样:if not first_start:...
您需要跟踪汽车是否启动。您还可以使用match/case实现代码的高级结构(需要Python 3.10)。例如:
started = False
while True:
match input('Enter command: ').lower():
case 'start':
if started:
print('Already started')
else:
print('Car started')
started = True
case 'stop':
if started:
print('Car stopped')
started = False
else:
print('Car not started')
case 'quit':
print('Goodbye')
break
case 'help':
print('''
start-to start the car
stop-to stop the car
quit-to exit
''')
case _:
print("I don't understand that")
我有一个类似的问题,这就是我如何解决它希望对你有帮助。
if is_car_started == True:
print("car started already...")
else:
is_car_started = True
print("car started... ready to go")