-1

我正在做一个关于 python 的学校练习,如果他们的购买价格在 10 美元到 20 美元之间,它要求我给客户 20% 的折扣。然后在 21 美元到 30 美元之间购买可享受 30% 的折扣。每次我输入 21 到 30 之间的数字时,它都会给我 20% 和 30% 的折扣,我如何让它给我 30% 的折扣。pyscrpiter 在第 2 行中还说不可排序的类型。如何解决此错误

    productprice=input ('Enter price of product')
if productprice > 10:
        discount = productprice*0.80
if productprice> 20:
        discount = productprice*0.70
4

4 回答 4

6

Python3.x版本

productprice = float(input('Enter price of product'))
if 10.0 <= productprice <= 20.0:
    afterDiscount = productprice * 0.80
elif 20.1 <= productprice <= 30.0:
    afterDiscount = productprice * 0.70
else:
    afterDiscount = productprice
print (afterDiscount)

Python2.x版本

productprice = float(raw_input('Enter price of product'))

笔记

  1. 在 Python 中,您可以检查一个数字是否在给定范围内,如下所示。

    0 < num < 3
    

    如果它在数学上是有效的,那么它将返回TrueFalse否则。

  2. 有这个else角色总是好的。

于 2013-10-05T03:23:04.983 回答
2
productprice = float(raw_input('Enter price of product '))

if  30 >= productprice >= 21:
        productprice *= 0.70
elif  20 >= productprice >= 10:
        productprice *= 0.80

print(productprice)

您的输入必须转换为 int 或 float 才能与数字进行比较。此外,使用 elif 可确保您只提供一次折扣

于 2013-10-05T03:22:24.513 回答
2

您应该考虑使用“其他”。首先,如果您检查它是否在较低的价格范围内,如果是,则执行第一个 if 并忽略 else。您还需要进行复合语句 ( productprice >= 10 and productprice <= 20)。我不知道 python 如何处理读取输入,但您可能需要从字符串转换为整数来修复第 2 行错误。

于 2013-10-05T03:24:54.050 回答
1
productprice=int(input ('Enter price of product'))
if productprice > 20 and productprice < 31:
    discount = productprice*0.70
elif productprice> 10:
    discount = productprice*0.80
于 2013-10-05T03:17:37.103 回答