首先,我在python和编程方面都是完全noob,所以我只是想从这里和那里捕捉到一些东西并尽可能多地改进。 我有这段代码:
print ('\n')
country = ''
province = ''
gstTax = 0.05
hrmTax = 0.13
otherTax = gstTax + 0.06
car = 30000.42
shoes = 333.24
laptop = 1000.98
print 'Car added to the basket, price: {0:.2f} $'.format(car)
print 'Shoes added to the basket, price: {0:.2f} $'.format(shoes)
print 'Laptop added to the basket, price: {0:.2f} $'.format(laptop)
orderTotal = car + shoes + laptop
print ('\n')
country = str(raw_input('Country residence? ')).capitalize()
if country == 'Canada':
province = str(raw_input('Which province? ')).capitalize()
if province == 'Alberta':
print 'Your final payment: ', (orderTotal + gstTax), '$'
elif province == 'Ontario' or province == 'New Brunswick' \
or province == 'Nova Scotia':
print 'Your final payment: ', (orderTotal + hrmTax), '$'
else:
print 'Your final payment: ', (orderTotal + otherTax), '$'
else:
print 'Your final payment: ', (orderTotal), '$'
print 'Transaction ended, thank you for your purchase'
基本上我想添加的是购买前的一种选择(即:您选择的笔记本电脑产品成本太高,或者您选择了“鞋子”产品等等)。我知道有列表,但我不知道,但仍然了解它们的使用。也许有人可以指出我正确的方向。
答案 0 :(得分:2)
您可以做的是将添加到购物篮中的每件商品添加到itemsInBasketList
,以便您可以循环,打印商品并将商品价格一次性添加到订单总计中。这种类型的for循环将遍历列表中的每个项目,并让项目保存您可以使用的值。另一种方式(你可能更熟悉)是指标。通过这种方式,您可以获得索引并访问该索引处的列表项,并以此方式获取值。两者都完成了同样的事情,一个比另一个更容易编写和使用。
print ('\n')
country = ''
province = ''
gstTax = 0.05
hrmTax = 0.13
otherTax = gstTax + 0.06
car = 30000.42
shoes = 333.24
laptop = 1000.98
itemsInBasket = []
itemsInBasket.append('Car added to the basket, price: {0:.2f} $'.format(car))
itemsInBasket.append('Shoes added to the basket, price: {0:.2f} $'.format(shoes))
itemsInBasket.append('Laptop added to the basket, price: {0:.2f} $'.format(laptop))
orderTotal = 0
for item in itemsInBasket:
print item
if 'Car' in item:
orderTotal += car
elif 'Shoes' in item:
orderTotal += shoes
elif 'Laptop' in item:
orderTotal += laptop
country = str(raw_input('Country residence? ')).capitalize()
if country == 'Canada':
province = str(raw_input('Which province? ')).capitalize()
if province == 'Alberta':
print 'Your final payment: ', (orderTotal + gstTax), '$'
elif province == 'Ontario' or province == 'New Brunswick' \
or province == 'Nova Scotia':
print 'Your final payment: ', (orderTotal + hrmTax), '$'
else:
print 'Your final payment: ', (orderTotal + otherTax), '$'
else:
print 'Your final payment: ', (orderTotal), '$'
print 'Transaction ended, thank you for your purchase'