[英]Please I would like to understand this code better
import sys
import time
command=""
started=False
while True:
name=input("Enter your name! ")
if name!="":
break
if len(name)<3:
print("name's too short ")
time.sleep(1)
exit()
answer=input(f"Hello {name} do you want to play my game! ").lower()
if answer== "yes":
while command!=("quit"):
command=input("press 's' to start, p to pause or q to quit ").lower()
if command==("s"):
if started:
print('car already started')
else:
started=True
print("car started")
elif command==("p"):
if not started:
print('car already stopped')
else:
started=False
print("car stopped")
elif command==("q"):
print("game ended")
time.sleep(2)
exit()
else:
print(" i dont understand")
When I run this code and I press 's' to start I get 'car started' and when I tried pressing 's' again I get car already started but I got confused at "started=True Print("car started")".当我运行此代码并按“s”启动时,我得到“汽车启动”,当我再次尝试按“s”时,我的汽车已经启动,但我对“started=True Print("car started")”感到困惑. I was wondering since started is set to True shouldn't the print statement be ("car already started") although the program is working good but when looking at the code I am just a bit confused and please I would need a bit clarification on the code.
我想知道既然 started 设置为 True 打印语句不应该是(“car already started”)虽然程序运行良好但是在查看代码时我只是有点困惑并且我需要一些澄清代码。
As you are confused about the started = True
part, I will try and focus on that mainly.由于您对
started = True
部分感到困惑,我将尝试主要关注它。
What the if started
condition does is checks if you have already typed s
beforehand. if started
条件的作用是检查您是否已经预先输入了s
。 If you have, ie if started
, then print('car already started')
runs.如果你有,即
if started
,然后print('car already started')
运行。
You may be confused about the if
statement not having a condition, ie if started
.您可能对没有条件的
if
语句感到困惑,即if started
。 This is just a shorthand for writing if started == True
, as an if statement evaluates the condition based on True
or False
.这只是
if started == True
的简写,因为 if 语句根据True
或False
评估条件。
Once the user has typed s
and hasn't typed s
before, the boolean started
is set to True
(previously False) and print("car started")
runs.一旦用户输入了
s
并且之前没有输入过s
,boolean started
将设置为True
(之前为 False)并运行print("car started")
。 This ensures that the next time you type s
, the if
statement runs again, and since if started
is true, print('car already started')
runs.这确保下次您键入
s
时, if
语句再次运行,并且由于if started
为真,则print('car already started')
运行。
The if not
statement checks the opposite, ie if not started
means the same thing as if started == False
. if not
语句检查相反的情况,即if not started
与if started == False
意思相同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.