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