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

2024-06-07 09:28:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在做一个自动售货机程序,我需要禁用的产品没有足够的信用选项,我如何缩短我的代码,而不是使用if语句:抱歉的混乱,我需要检查他们是否有足够的钱为该产品如果他们没有那么该产品不应该被列为在自动售货机销售

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

Tags: 代码程序youif产品选项语句can
3条回答

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

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))

通过使用类,可以为不同的属性指定有意义的名称。您还可以定义方法来确定诸如可承受性之类的事情,并为特定类型的商品派生类。你知道吗

也许一个可购买的价格清单对你在自动售货机上实现这一点会更好。你知道吗

[price for price in prices if price <= float(money)]

我建议使用for循环:

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

不确定您的其余数据是如何存储/显示的,因此可能需要对您的问题/本文进行进一步的编辑。你知道吗

相关问题 更多 >

    热门问题