我有下面寫的代碼,程式的目標是讓用戶在一個串列中列出所有汽車,然后通過輸入詢問一輛特定汽車的具體細節。但是,當用戶輸入他們想要詳細資訊的汽車時,它還會列印 txt 檔案中的所有汽車,而不僅僅是那一輛車。
撰寫程式的主檔案中的代碼:
while True:
command = input("(L)ist all cars, get a cars (D)etails, or (Q)uit: ").strip().lower()
if command == "q":
break
if command == "l":
for car in cars:
car.displayCar()
elif command == "d":
carName = input("Enter car name: ").strip().lower()
for car in cars:
if car.is_match(carName):
car.display()
else:
print("Invalid command")
上面用于呼叫用戶輸入的檔案中的代碼:
def is_match(self, carName):
if self.carName == True:
return False
if carName == self.carName:
return False
return True
uj5u.com熱心網友回復:
def is_match(self, carName):
if self.carName == True:
return False
if carName == self.carName:
return True
return False
您在 is_match 函式中混淆了真偽。我敢打賭,如果你真的檢查,你會發現它列印出了除了查詢汽車的行之外的每一行。
uj5u.com熱心網友回復:
要回答您的問題的標題,因為我對您還問什么感到困惑:
with open(file,mode) as name:
name.read() #Reads whole file
name.close()
現在對于 is_match():
def is_match(self, carName):
if self.carName == True:
return True
if carName == self.carName:
return False
return False
uj5u.com熱心網友回復:
據我了解,如果給定的字串與汽車類中的汽車名稱匹配,則需要列印汽車詳細資訊。
def is_match(self, carName):
if(self.carName):
return self.carName.lower()==carName
如果您可以上傳帶有示例輸入和輸出的完整代碼,那就太好了
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/466423.html
標籤:Python python-3.x
