需要Python编程帮助吗?

-1 投票
4 回答
1049 浏览
提问于 2025-04-17 06:34

我一直在尝试写一个像收银机一样的代码,用户可以输入产品名称、价格和数量。我有四种产品。在把这些加起来之后,我需要计算5%的商品和服务税(GST),然后打印出包含税费的总金额。这是我目前能做到的,因为我刚开始学Python,所以对很多错误和其他关键词不太了解。我在所有地方都能输入数据,但当我尝试进行乘法运算时,系统提示我不能将字符串和整数相乘。我试着换了变量名,也做了其他尝试,但就是无法得到总金额。

name1 =raw_input('What Item do you have: ')
price1 = float(input('What is the price of your item: '))
quantity1 = float(input('How many are you buying: '))
name2 = raw_input('What Item do you have: ')
price2 = float(input('What is the price of your item: '))
quantity2 = float(input('How many are you buying: '))
name3 = raw_input('What Item do you have: ')
price3 = float(input('What is the price of your item: '))
quantity3 = float(input('How many are you buying: '))
name4= raw_input('What Item do you have: ')
price4 = float(input('What is the price of your item: '))
quantity4 = float(input('How many are you buying: '))
sum_total= (price1 * quantity1), (price2 * quantity2), (price3 * quantity3), (price4 * quantity4),
print(' %.2f ' %  quantity1+quantity2+quantity3,' X ', name1+name2+name3,' @ %.2f ' %  
price1+ price2+price3,' = %.2f ' % total)
divv = sum_total / 100
percent = divv * 0.05
gst = sum_total + percent
print('The suggested gst is %.2f '% percent )
print('That will be a total of: %.2f '% gst)

4 个回答

1

我在这里看到很多奇怪的事情。我建议你可以这样做:

  1. 先写一个程序,让它能处理一个产品。
  2. 然后再添加第二个产品。
  3. 接下来考虑使用循环。

如果你在某个步骤遇到困难,可以在这里提问。

1

什么是 sum_total?

你写的是

sum_total = something, something else, something else again

(注意那个“,”)

是不是写成这样会更好呢

sum_total = something + something else + something else again

?(注意那个“+”号)

你第一行写的是一个元组(可以去查查 Python 的文档!),而不是一个数字。

1

这可以简化很多。

你用来询问产品的代码可以简化成这样:

def ask_for_products(how_many):
    products = []
    for i in xrange(how_many):
        product = {
            'name': raw_input('What Item do you have: '),
            'price': float(input('What is the price of your item: ')),
            'quantity': float(input('How many are you buying: '))
        }
    products.append(product)
    return products

这样做会让你的代码更加灵活和模块化。

总和可以这样计算(假设products包含了上面函数的结果):

total_sum = sum([i['price']*i['quantity'] for i in products])

如果我理解得没错,建议的GST是:

suggested_gst = .05 * total_sum

你还可以打印出产品的列表,包括价格和数量

for p in products:
    print '%.2f X %.2f %s' % (p['quantity'], p['price'], p['name'])

撰写回答