【问题标题】:Python - Making arguments to a function optionalPython - 使函数的参数可选
【发布时间】:2019-05-19 21:42:01
【问题描述】:

我正在学习构建一个 Python 函数,该函数从用户那里获取一些输入并将其传递给函数以作为 SQL 语句的一部分执行。

def sales(sale_date,prod_type,prod_category):
    db.execute("""select prod_name,quantity,price_per_product from sales 
                      where sale_date = (%s) and prod_type = (%s) and prod_category =(%s)""",
                      (sale_date,prod_type,prod_category)

我想知道如何修改上述函数,以便如果未提供其中一个参数,我仍将执行该函数,但缺少的参数不会被添加为过滤器。

即如果 sale_date 为 Null(或 None),我该如何修改上述函数。谢谢

【问题讨论】:

    标签: python-3.x arguments parameter-passing


    【解决方案1】:

    如何使用默认参数并单独处理案例?看看这个sn-p:

    def sales(sale_date=None, prod_type=None, prod_category=None):
    
        if sale_date is not None and prod_type is not None and prod_category is not None:
            db.execute("""select prod_name,quantity,price_per_product from sales 
                          where sale_date = (%s) and prod_type = (%s) and prod_category =(%s)""",
                          (sale_date,prod_type,prod_category)
        # Handling other cases
        elif ... :
            pass
        else:
            pass
    

    您可以为要涵盖的每个案例提供单独的 SQL 语句。

    【讨论】:

      猜你喜欢
      • 2023-03-21
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      相关资源
      最近更新 更多