How to return if-else one line in Python function?
It is simple you can write if block statements into a single line with the default return value in the return statement of function.
You can check out the ternary operator (conditional expression):
Example Python return if-else one line
Return true if the letter “e” is present in the string or word.
def hasLetter(word):
return True if 'e' in word else False
print(hasLetter("Test"))
Output:
Example Python One Line Return if
def f(x):
return None if x == 0
Write the return statement with an if expression in a single line of Python code example. Print the results of all three function executions for a given value.
# Method 1
def f1(x):
if x == 0:
return None
# Method 2
def f2(x):
if x == 0: return None
# Method 3
def f3(x):
return None if x == 0 else 7
# Test
print(f1(10))
print(f2(10))
print(f3(10))
Output:
None
None
7
Do comment if you have any doubts and suggestions on this Python if-else topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.