38

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.

3
  • 1
    there is nothing called two return statements! return (n<m)? n:m returns only one value, either n or m, based on the comparison n<m Commented Sep 3, 2012 at 18:31
  • @Curious I had a weird confusion,now its clear. Commented Sep 3, 2012 at 18:33
  • 1
    in python you could write the same thing as return n if n<m else m Commented Sep 3, 2012 at 18:34

2 Answers 2

74

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.