Return statement using ternary operator

Question:

In c I can do something like:

int minn(int n, int m){
 return (n<m)? n:m
}

But in python I am not able to achieve the same:

def minn(n,m):
    return n if n<m else return m

this gives Syntax Error

I know I can do something like :

def minn(n,m):
    return min(n,m)

My question is that, can’t I use ternary operator in python.

Asked By: Ashwini Chaudhary

||

Answers:

Your C code doesn’t contain two return statements. Neither should your python code… The translation of your ternary expression is n if n<m else m, so just use that expression when you return the value:

def minn(n,m):
    return n if n<m else m
Answered By: Karoly Horvath
def minn(n,m):
    return n if n<m else m

The expr1 if expr2 else expr3 expression is an expression, not a statement. return is a statement (See this question)

Because expressions cannot contain statements, your code fails.

Answered By: unddoch
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.