Is is possible to return from a method in single line in python
Looking for something like this
return None if x is None
Tried above, and it is invalid syntax
I could easily do:
if x is None: return None
But just curious if I can combine above if statement into a single line
The value of expression, if present, is returned to the calling function. If expression is omitted, the return value of the function is undefined. The expression, if present, is evaluated and then converted to the type returned by the function.
Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.
Other programming languages like C++ and Java have ternary operators, which are useful to make decision making in a single line. Python does not have a ternary operator. But in python, we can use the if-else in a single line, and it will give the same effect as the ternary operator.
We can use the return statement inside a function only. In Python, every function returns something. If there are no return statements, then it returns None. If the return statement contains an expression, it's evaluated first and then the value is returned.
Yes, it's called a conditional expression:
return None if x is None else something_else
You need an else something
in a conditional for it to work.
It is possible to write a standard "if" statement on a single line:
if x is None: return None
However the pep 8 style guide recommends against doing this:
Compound statements (multiple statements on the same line) are generally discouraged
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