Python Boolean

Python Boolean is one of the two values True or False.

In any programming language, if we validate any expression, we are going to get either True or False as an answer.

print(3>5)
print(5==5)

In the above example, we are validating an expression and getting the boolean value as an answer.  As we have seen in previous tutorials, the if and while loops are executing a piece of code based the boolean value returned by the expression.

Evaluating Values with Python Boolean:

The bool() function is used to evaluate any value and returns an answer which is either True or False.

Any value is True unless it’s empty.

The below examples will return True.

print(bool(1))
print(bool("ABC"))
print(bool([1,2,3]))

The below examples will return False because they are empty values.

print(bool(""))
print(bool(0))
print(bool([]))
print(bool(()))
print(bool({}))

Booleans in functions:

We will be covering functions in the upcoming tutorial. At this point its enough to know that a function can return a boolean value and we can also execute a piece of code based on the return value of the function.

def function():
  return True
if function():
  print("YES")
else:
  print("NO")

In python def indicates a function. The name followed by the def keyword is the name of the function. The above code contains a function, function() which does nothing but returns a boolean value.

And then we are printing “YES” or “NO” based on the return value of the function.

 

Translate »