37

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.

Adam Parkin
  • 17,891
  • 17
  • 66
  • 87
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504

2 Answers2

72

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
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • 1
    Hmm. Kinda obvious if you think about it, but considering I have a computer science degree and 4 years of Java/Software Engineering experience, I was still scratching my head on this one. Thanks for posting. – Leo Ufimtsev May 02 '19 at 13:11
14
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.

Community
  • 1
  • 1
unddoch
  • 5,790
  • 1
  • 24
  • 37