2016-06-11 31 views
0

我在一個項目上工作,但我似乎無法弄清楚這一整個while循環的事情。我正在創建一個小小的收據程序,我可以獲得用戶輸入他們物品的價格,然而他們想要輸入的很多。但我不知道如何告訴程序添加他們輸入的所有項目來創建小計。輕鬆點我,我只是一個初學者。以下是我目前使用的代碼:如何在while循環中將變量分配給價格以獲得小計?

import locale 
locale.setlocale(locale.LC_ALL, '') 

print("Welcome to Publix".center(80)) 


while(True): 
    Price = float(input("Price of item: ")) 
    if(Price == -1): 
     break 





print("Thank you for shopping at Publix!".center(80)) 
#Tax = Subtotal * 0.065 
+0

爲什麼我的回答不被接受? –

回答

1

您需要在循環前將小計初始化爲0,並將價格每次添加到小計。

import locale 
locale.setlocale(locale.LC_ALL, '') 

print("Welcome to Publix".center(80)) 

Subtotal = 0 
while(True): 
    Price = float(input("Price of item: ")) 
    if(Price == -1): 
     break 

    Subtotal = Subtotal + Price 





print Subtotal; 
print("Thank you for shopping at Publix!".center(80)) 
#Tax = Subtotal * 0.065 
+0

我在我的代碼中輸入了這個值,但是在輸入-1之後我還沒有得到小計 – Zjm4192

+0

爲此,您需要在循環外打印小計 –

+0

@ Zjm4192:更新了代碼 –

0

使用變量(subtotal)來累計價格值。您可以添加一個try-except-else塊,以防止錯誤的用戶輸入無法轉換爲浮動破壞您的代碼。有了這個,你的代碼是一個小bug更少:

import locale 
locale.setlocale(locale.LC_ALL, '') 

print("Welcome to Publix".center(80)) 

subtotal = 0 
while True: 
    try: 
     price = float(input("Price of item (enter -1 to stop): ")) 
     if price == -1: 
      break 
    except ValueError: 
     print("The format of the price you entered is not acceptable") 
    else: 
     subtotal += price 

print("Thank you for shopping at Publix!".center(80)) 
# tax = subtotal * 0.065 

我建議你使用decimal對與準確性的原因存儲你的價格。