首页 > 解决方案 > 如果传递了另一个参数,则 Python 函数使参数成为强制性参数

问题描述

我在 Python 中有一个函数作为

def myfunc(a, b=None, c=None):
    my code here

有没有办法确保如果用户传递参数的值,b则必须将参数传递cmyfunc

标签: pythonuser-defined-functions

解决方案


您可以在函数中编写一个简单的if条件。请看下面的代码:

def myfunc(a, b=None, c=None):
    if c is not None and b is None:
        raise ValueError("Value of b must be passed if value of c is passed")
    your code here

推荐阅读