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"))
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))
Do comment if you have any doubts and suggestions on this Python if-else topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.