Py04: Boolean
Boolean is used in programming to imitate real-world situations. It is used in decision-making and loop statements. A boolean expression is an expression that gives boolean values as result.
Introduction
Boolean data type only has true or false values. In Python, True and False keywords are used to represent boolean values. A boolean variable is created by assigning True or False to a variable.
variableName = [True|False]
For example, light_is_on is a boolean variable with the value True.
light_is_on = True
The boolean variable can be used in the if statement as follows:
light_is_on = True
if light_is_on:
print("Light is On")
else:
print("Light is Off")
Output
Light is On >
Just in case if we want the check the type for the variable light_in_on variable, we can use the type() function.
light_is_on = True
print(type(light_is_on))
Output
<class 'bool'> >
Checking Boolean value
to check if a given value is True or False, we can use the bool()
function. (The hash show preview of the output)
print(bool(0)) # False
print(bool(25)) # True
print(bool("hello")) # True
print(bool(None)) # False
Output
False True True False >
The bool() function returns False if the value is:
- 0 or 0.0 (the number zero)
- '' or "" (empty string)
- False (the False keyword)
- None (the None keyword)
- [] (empty list)
- () (empty tuple)
- {} (empty dictionary)
The bool() function returns True if the values are not false.
Comparison operator
Comparison operators return a boolean value as result. Comparisons are used in decision-making and loop statements.
Operator | Name | Usage |
---|---|---|
< | less than | a < b |
> | greater than | a > b |
<= | less than or equal to | a <= b |
>= | greater than or equal to | a >= b |
== | equal to | a == b |
!= | not equal to | a != b |
The following example shows how the comparison operator works to check the relationship between 30 and 45.5. (The hash show preview of the output)
num1 = 30
num2 = 45.5
print(num1 < num2)
print(num1 > num2)
print(num1 <= num2)
print(num1 >= num2)
print(num1 == num2)
print(num1 != num2)
Output
True False True False False True >
A post by Cuber
Comments
Post a Comment