有没有办法缩短这段代码?
price1 = input("\nEnter price here: ")
price1 = int(price1)
price2 = input("\nEnter price here: ")
price2 = int(price2)
price3 = input("\nEnter price here: ")
price3 = int(price3)
price4 = input("\nEnter price here: ")
price4 = int(price4)
price5 = input("\nEnter price here: ")
price5 = int(price5)
price6 = input("\nEnter price here: ")
price6 = int(price6)
price7 = input("\nEnter price here: ")
price7 = int(price7)
price8 = input("\nEnter price here: ")
price8 = int(price8)
price9 = input("\nEnter price here: ")
price9 = int(price9)
price10 = input("\nEnter price here: ")
price10 = int(price10)
total = price1 + price2 + price3 + price4 + price5 + price6 + price7 + price8 + price9 + price10
grand_total = (18 * total /100 + total)
print("\nThe total amount weill equil to", grand_total, "(with 18% V.A.T)")
答案 0 :(得分:11)
prices = [] # an empty list
for i in range(10):
price = int(input("\nEnter price here: "))
prices.append(price) # append price to list
total = sum(prices)
然后,您可以参考每个单独的价格,例如prices[index]
答案 1 :(得分:3)
您可以使用累加器值:
total = 0
for i in range(10):
total += int(input("\nEnter price here: "))
grand_total = 18 * total / 100 + total
print("\nThe total amount will equal to", grand_total, "(with 18% V.A.T)")
答案 2 :(得分:3)
Protip:避免使用float
来处理金钱以避免舍入错误
from decimal import Decimal
def get_price():
return Decimal(input("\nEnter price here: "))
total = sum(get_price() for i in range(10))
grand_total = total * Decimal("1.18")
答案 3 :(得分:2)
使用生成器表达式:
total = sum( int(raw_input("\nEnter price here: ")) for i in xrange(10) )
grand_total = int(1.18 * total) # intended integer division?