Assign the Boolean value to a variable and return it, it will make the function always returns a value True or False in Python. Discover code examples and different ways to implement functions in Python.
def foo(x, y):
answer = False
if x > y:
answer = True
else:
answer = False
return answer
print("X is Greater then Y: ", foo(12, 5))
Output:
Another example
A function that always returns True
(or False
) for every parameter (or even multiple parameters).
false = lambda *_: False
true = lambda *_: True
In Python, a function can return a value of any data type, including True
or False
. For example, consider the following function that checks if a given number is even:
def is_even(num):
if num % 2 == 0:
return True
else:
return False
This function takes an argument num
and returns True
if the number is even, and False
otherwise.
Alternatively, you can simplify the function using the ternary operator, like this:
def is_even(num):
return True if num % 2 == 0 else False
This function does the same thing as the previous one, but in a more concise way.
Comment if you have any doubts or suggestions on this Python example code.
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.