[英]Python 3: Append integers on a list with while True loop
我正在嘗試做以下練習:
任務 4
創建一個空列表 purchase_amounts 用用戶輸入的項目價格填充列表繼續添加到列表中直到輸入“完成”
可以使用 while True: with break
打印購買金額
這是我到目前為止的代碼:
#[ ] complete the Register Input task above
purchase_amounts=[]
purchase_amounts.append(input("Enter the prices: "))
while True:
if input("Enter the prices: ") != "done":
purchase_amounts.append(input("Enter the prices: "))
else:
break
print(purchase_amounts)
但它給了我一個非常奇怪的 output 像這樣:
輸入價格:2222222
輸入價格:1
輸入價格:2
輸入價格:3
輸入價格:完成
輸入價格:完成
['2222222', '2', '完成']
有誰知道為什么它會覆蓋第二個、第四個和第五個輸入並且它沒有將值添加到列表中? 非常感謝!
您有 2 個 input(),但實際上只使用了一個。 檢查評論:
while True:
if input("Enter the prices: ") != "done": #Here you only compare the input with "done" but you don't do anything with it
purchase_amounts.append(input("Enter the prices: ")) #here you ask for a second input
您只能要求輸入一次並將其保存在變量中:
while True:
value_input = input("Enter the prices: ")
if value_input != "done":
purchase_amounts.append(value_input)
else:
break
PS:您可能想將字符串轉換為int,不是嗎?
你接受輸入的次數太多了。
您應該通過調用input()
在每個循環中只接受一次輸入,然后添加到列表中。 您可能還想將輸入轉換為帶有float
的數字。
purchase_amounts=[]
while True:
user_input = input("Enter the prices: ")
if user_input != "done":
purchase_amounts.append(float(user_input))
else:
break
print(purchase_amounts)
Output:
Enter the prices: 12
Enter the prices: 13
Enter the prices: done
[12, 13]
嘗試與 IF 分開使用測試用例。
請注意,!= 的 python 方式not (test case)
purchase_amounts=[]
# purchase_amounts.append(input("Enter the prices: ")) <- this can be sacked
while True:
test_case = input("Enter the prices: ")
if not test_case == "done":
purchase_amounts.append(input("Enter the prices: "))
else:
break
print(purchase_amounts)
purchase_amounts=[]
while True:
a=input("Enter price of Items :")
if a=='Done':
break
else:
purchase_amounts.append(a)
print(purchase_amounts)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.