Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return statement using ternary operator

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.

like image 747
Ashwini Chaudhary Avatar asked Sep 03 '12 18:09

Ashwini Chaudhary


People also ask

Can you use ternary operator in return statement?

The ternary operator isn't meant to execute an action or another but rather to yield a value or another. You can abuse it in much cases since most actions will return undefined or something more appropriate, but you can't do that with return .

Can we use return in ternary operator in Java?

The Java ternary operator can be thought of as a simplified version of the if-else statement with a value to be returned. It consists of a Boolean condition that evaluates to either true or false, along with a value that would be returned if the condition is true and another value if the condition is false.

What is the return type of ternary operator in Java?

If the first operand is true then java ternary operator returns second operand else it returns third operand. Syntax of java ternary operator is: result = testStatement ? value1 : value2; If testStatement is true then value1 is assigned to result variable else value2 is assigned to result variable.

What is ternary operator with example?

A ternary operator lets you assign one value to the variable if the condition is true, and another value if the condition is false. The if else block example from above could now be written as shown in the example below. var num = 4, msg = ""; msg = (num === 4) ?


1 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 
like image 126
Karoly Horvath Avatar answered Sep 23 '22 13:09

Karoly Horvath