2016-02-25 94 views
-1
price = int(input('Enter price. ')) 
quan = int(input('Enter quantity. ')) 
total = price*quan 
print('The total is ' +str(total)) 

price2 = int(input('Enter price. ')) 
quan2 = int(input('Enter quantity. ')) 
total2 = price2*quan2  

all_totals = total + total2 
print('The sum of the totals is ' +str(all_totals)) 

理想情況下,我不想有price2等,但我需要程序來循環和加起來的小計,然後打印什麼是總的。我是新來的python和任何幫助表示讚賞。謝謝!我該如何循環這段代碼?

回答

4
grandtotal = 0 

while True: 
    price = int(input('Enter price. (0 to quit) ')) 
    if price == 0: 
     break 
    quan = int(input('Enter quantity. ')) 
    subtotal = price*quan 
    print('The subtotal is %d' % subtotal) 
    grandtotal = grandtotal + subtotal 

print('The sum of the totals is %d' % grandtotal) 
+0

非常感謝!我現在知道了。我感謝您的幫助! –

+0

upvoted。既然你在那裏,也許,建議更好地使用'print' – Pynchia