首页 > 解决方案 > 想出一个python代码来解决下面的问题

问题描述

假设一本书的封面价格是 24.95 美元,但书店可以获得 40% 的折扣。第一份运费为 3 美元,每增加一份运费为 75 美分。60 份的总批发成本是多少?

这是我尝试过的:

    a='coverprice'
    >>> b='discount'
    >>> c='shipping costs'
    >>> d='additional copies'
    >>> e='no. of copies'
    >>> a=24.95
    >>> b=0.4
    >>> c=3
    >>> d=0.75*59
    >>> e=60
    >>> print ('total costs=',c+d)
    total costs= 47.25
    >>> f='total cost'
    >>> print ('total discount=',b*a)
    total discount= 9.98
    >>> g='total discount'
    >>> print('total purchase cost before discount=',a*e)
    total purchase cost before discount= 1497.0
    >>> h='total purchase cost before discount'
    >>> print('total purchase cost after discount=',h-g)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for -: 'str' and 'str'
    >

标签: python

解决方案


你得到的错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

是因为你试图减去字符串而不是数字:

>>> g='total discount'
...
>>> h='total purchase cost before discount'
>>> print('total purchase cost after discount=',h-g)

鉴于所描述的问题和所采取的方法,我可能会这样处理:

a = 24.95  # cover price
b = 0.4  # discount
c = 3.00  # initial shipping cost
d = 0.75  # additional items shipping cost
e = 60  # no. of copies

f = c + d * (e - 1)  # total shipping cost
print(f"total shipping cost = ${f:0,.2f}")

g = a * b  # discounted book cost
print(f"discounted book cost = ${g:0,.2f}")

h = a * e  # total purchase cost before discount (sans shipping)
print(f"total purchase cost before discount (sans shipping) = ${h:0,.2f}")

i = g * e  # total purchase cost after discount (sans shipping)
print(f"total purchase cost after discount (sans shipping) = ${i:0,.2f}")

j = h - i  # total discounted savings
print(f"total discounted savings = ${j:0,.2f}")

输出

> python3 test.py
total shipping cost = $47.25
discounted book cost = $9.98
total purchase cost before discount (sans shipping) = $1,497.00
total purchase cost after discount (sans shipping) = $598.80
total discounted savings = $898.20
>

推荐阅读