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.
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 .
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.
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.
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) ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With