如何缩短我的代码而不是使用几个if语句:

时间:2015-12-30 13:58:47

标签: python

我正在制作一个自动售货机程序我需要禁用产品的选项,这些产品没有足够的功劳,如何缩短我的代码而不是使用if语句:对不起因为混乱,我需要检查他们是否有足够的钱该产品如果不存在那么该产品不应列入自动售货机销售

    prices = [30.50,45,90,89]
    money = "30"
    if money != prices[0]:
        print("option disabled")
    else:
        print("you can buy this")

3 个答案:

答案 0 :(得分:1)

我建议使用for循环:

for price in prices:
    if money >= price:
        print("You can buy this")
    else:
        print("Option disabled")

不确定如何存储/显示其余数据,以便进一步修改您的问题/这篇文章可能是必要的。

答案 1 :(得分:1)

我建议创建一个产品列表,每个产品都有一定的属性(理想情况下,您可以实现一个代表产品的类)。然后,您可以遍历每个产品并检查价格等条件:

product_list = []

# Add some products to the list
# [ Name, Price, Summer Only, Sale ]
product_list.append(['Apple', 5.50, true, false])
product_list.append(['Orange', 9.0, false, false])
product_list.append(['Spam', 0.5, false, true])

# Suppose the user has some money
money = 5.0

for prd in product_list:
    if prd[1] > money:
        print("You can buy {0}".format(prd[0]))
    elif prd[3] and prd[1]*0.1 > money:
        print("Yay, {0} is on sale.  You can buy {0}".format(prd[0]))

更好的选择是创建一个用于存储产品信息的类:

class Product:
    def __init__(self, name, price, summer, sale):
        self.name = name
        self.price = price
        self.is_summer = summer
        self.is_sale = sale

    def is_affordable(self, money):
        if self.is_sale: return self.price*0.1 <= money
        return self.price <= money

# Then you can again have a list of product
my_products = []
my_products.append(Product('Apple', 5.5, true, false))
my_products.append(Product('Spam', 0.1, false, true))

money = 5.0

for prd in my_products:
    if prd.is_sale:
        print("---- We are currently having a sale on {1} ---".format(prd.name))
    if prd.is_affordable(money):
        print("You can afford to buy {0}".format(prd.name))
    else:
        print("You can not afford to buy {0}".format(prd.name))

通过使用类,您可以为不同的属性分配有意义的名称。您还可以定义用于确定可承受性等事项的方法,并为特定类型的商品派生类。

答案 2 :(得分:0)

也许可购买的价格清单会更好地在自动售货机中实现。

[price for price in prices if price <= float(money)]
相关问题