Carmen
Carmen

Reputation: 793

Consecutive if-conditions in function, Python

I am creating a function which calulates an outcome depending on parameters in the formula.

Separately to the first if-function I'd like to add a second condition for cases in which n is not None

def target_n(data, y, q = None, s = 1, n = None, ascending = True):
        if q is not None:
            target = quantile(data, q, s)
            return(target)
        else:
            target = y(data,s)
            return(target)
        if n is not None:
            sort = target.sort(tst.columns[0],ascending = ascending).ix[0:n,:]
        return(sort)

Nevertheless the function returns "target" and not "sort" for cases in which n is not None. How can I implement this?

Upvotes: 1

Views: 83

Answers (1)

Julien Marrec
Julien Marrec

Reputation: 11895

Your problem is that you have a return statement whether q is None or not. As soon as the execution reaches the return statement, it exits the function.

You could do something like this

def target_n(data, y, q = None, s = 1, n = None, ascending = True):
    if q is not None:
        target = quantile(data, q, s)
    else:
        target = y(data,s)
    if n is not None:
        target = target.sort(tst.columns[0],ascending = ascending).ix[0:n,:]

    return(target)

Upvotes: 1

Related Questions