[英]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")
當我運行此代碼並按“s”啟動時,我得到“汽車啟動”,當我再次嘗試按“s”時,我的汽車已經啟動,但我對“started=True Print("car started")”感到困惑. 我想知道既然 started 設置為 True 打印語句不應該是(“car already started”)雖然程序運行良好但是在查看代碼時我只是有點困惑並且我需要一些澄清代碼。
由於您對started = True
部分感到困惑,我將嘗試主要關注它。
if started
條件的作用是檢查您是否已經預先輸入了s
。 如果你有,即if started
,然后print('car already started')
運行。
您可能對沒有條件的if
語句感到困惑,即if started
。 這只是if started == True
的簡寫,因為 if 語句根據True
或False
評估條件。
一旦用戶輸入了s
並且之前沒有輸入過s
,boolean started
將設置為True
(之前為 False)並運行print("car started")
。 這確保下次您鍵入s
時, if
語句再次運行,並且由於if started
為真,則print('car already started')
運行。
if not
語句檢查相反的情況,即if not started
與if started == False
意思相同。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.