Saeed
Saeed

Reputation: 2099

How to check if a function input is given or not?

Please consider this function that accepts two arguments: series and categorical_values. Its goal is to get a series, make it categorical, and then print each element of the original series alongside the categorized corresponding element. However, if the categorical_values is already passed to the function as an input, the categorization stage is skipped and the function simply prints the pairs of the passed series and categorical_values.

def my_function(series, categorical_values = None):

    if categorical_values: #meant to mean "if this argument is passed, just use it"
        categorical_values = categorical_values

    else: #meant to mean "if this argument is not passed, create it"
        categorical_values= pd.qcut(series, q = 5)

    for i,j in zip(series, categorical_values):
        print(i, j)

However, passing categorical_values in the following:

my_function(series, pd.qcut(series, q = 5))

leads to:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

The code line where this error results from is the very first line: if categorical_values:

What is the proper way to check if a function argument has been passed or is not?

Upvotes: 2

Views: 88

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599956

Since the default is None, you should just check it is not that.

if categorical_values is not None:
    ...

But that if block is a no-op anyway; it would be better to reverse it:

if categorical_values is None:
    categorical_values = pd.qcut(series, q = 5)

and you don't need an else block at all.

Upvotes: 6

Related Questions