【发布时间】:2022-12-04 11:48:16
【问题描述】:
我是编码新手,所以我一直在做练习。这是关于用户命令启动和停止的汽车。我的问题是为什么给定的解决方案包含以下代码中的第一行?:
command = ""
started = False
while True:
command = input("> ").lower()
if command == "start":
if started:
print("The car has already started")
else:
started = True
print("The car started")
elif command == "stop":
if not started:
print("The car has already stopped")
else:
started = False
print("The car stopped")
elif command == "quit":
print("Goodbye!")
break
elif command == "help":
print("""start - start the car
stop - stop the car
quit- quit the game""")
else:
print("Sorry, I don't understand")
我尝试删除第一行并运行代码,据我所知它运行良好。如果我遗漏了一些明显的东西,我深表歉意!
【问题讨论】:
-
没有。迷信而已。也许他们一开始说的是
while command != 'quit':而不是无限循环。 -
如果这是整个代码就没有用,否则这个对象可以在
while代码块之后使用 -
简短回答:这是 python,你不需要像在第一行那样实例化一个字符串
-
@TimRoberts 你是对的;他们从 while command != "quit" 开始,然后将其删除以证明它可以简化。令人印象深刻的是,您可以推断出这一点。
标签: python