Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to write single line return statement with if statement?

Tags:

python

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

like image 977
user462455 Avatar asked Sep 07 '13 04:09

user462455


People also ask

Can we use return in if statement?

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.

How do you do an IF line with one statement?

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.

Can we write if-else in one line?

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.

Can we use return with IF statement in Python?

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.


2 Answers

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.

like image 83
TerryA Avatar answered Oct 12 '22 23:10

TerryA


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

like image 31
nakedfanatic Avatar answered Oct 13 '22 00:10

nakedfanatic