0

有什么办法可以缩短这段代码吗?

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)")
4

4 回答 4

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]

于 2012-05-23T21:06:07.180 回答
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)")
于 2012-05-23T21:08:19.963 回答
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")
于 2012-05-23T21:51:32.713 回答
2

使用生成器表达式:

total = sum( int(raw_input("\nEnter price here: ")) for i in xrange(10) )
grand_total = int(1.18 * total) # intended integer division?
于 2012-05-23T21:09:46.283 回答