這個問題在這里已經有了答案: “==”和“是”有區別嗎? (14 個回答) 2 天前關閉。
我有一個簡單的代碼,它在開頭將一個變數設定為 0,然后根據串列中的輸入添加一個數字。但是每當添加完成時,輸出仍然是 0。我在每個陳述句后添加了一個列印來找出問題,但它總是輸出 0。我非常缺乏經驗,所以如果修復很簡單,我深表歉意。這是代碼:
HomeStartCodes = ["C1", "C2", "C3", "C4", "C5"]
HomeStartPrice = [1.5, 3.0, 4.5, 6.0, 8.0]
TotalPrice = 0.0
while True:
CCode = str(input("Please enter the first code of your journey "))
if (CCode not in HomeStartCodes):
print("Invalid, please enter C1. C2, C3, C4 or C5")
continue
else:
break
if CCode is str("C1"):
TotalPrice = TotalPrice HomeStartPrice[0]
if CCode is str("C2"):
TotalPrice = TotalPrice HomeStartPrice[1]
if CCode is str("C3"):
TotalPrice = TotalPrice HomeStartPrice[2]
if CCode is str("C4"):
TotalPrice = TotalPrice HomeStartPrice[3]
if CCode is str("C5"):
TotalPrice = TotalPrice HomeStartPrice[4]
print (TotalPrice)
輸出:
Please enter the first code of your journey C1
0.0
uj5u.com熱心網友回復:
因為您正在使用is(這是嚴格的身份比較,用戶輸入的字串將失敗)。
使用==(用于任何和所有比較,真的)。
HomeStartCodes = ["C1", "C2", "C3", "C4", "C5"]
HomeStartPrice = [1.5, 3.0, 4.5, 6.0, 8.0]
TotalPrice = 0.0
while True:
CCode = str(input("Please enter the first code of your journey "))
if (CCode not in HomeStartCodes):
print("Invalid, please enter C1. C2, C3, C4 or C5")
continue
else:
break
if CCode == "C1":
TotalPrice = TotalPrice HomeStartPrice[1]
if CCode == "C2":
TotalPrice = TotalPrice HomeStartPrice[2]
if CCode == "C3":
TotalPrice = TotalPrice HomeStartPrice[3]
if CCode == "C4":
TotalPrice = TotalPrice HomeStartPrice[4]
if CCode == "C5":
TotalPrice = TotalPrice HomeStartPrice[5]
print (TotalPrice)
此外,您可以通過使用字典將代碼映射到價格來簡化代碼,根本不進行這些比較:
HomeStartCodes = {
"C1": 1.5,
"C2": 3.0,
"C3": 4.5,
"C4": 6.0,
"C5": 8.0,
}
TotalPrice = 0.0
while True:
CCode = str(input("Please enter the first code of your journey "))
value = HomeStartCodes.get(CCode)
if not value:
print("Invalid")
continue
TotalPrice = value
print(TotalPrice)
uj5u.com熱心網友回復:
該is運營商的身份進行比較,這意味著你不匹配任何案件。您應該==用于字串比較。通常,您應該==用于比較True、False、 或以外的比較None。
此外, alist從 index 開始0,因此在解決第一個問題后,您將獲得下一個最高值(或IndexErrorfor C5)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/311501.html
