In Python, a Boolean is a data type that can have only two values: True
or False
. These values are often used to keep track of yes/no questions or on/off switches.
Here's an example:
is_raining = False
if is_raining:
print("Bring an umbrella!")
else:
print("No need for an umbrella today.")
In this example, the is_raining
variable is assigned the value False
, which means it is not currently raining.
So when we check the value of is_raining
in the if
statement, the else
block is executed and "No need for an umbrella today." is printed.
Boolean values are also often used with comparison operators to compare two values and see if they are equal, greater than, or less than each other. For example:
a = 5
b = 3
if a > b:
print(a, "is greater than", b)
In this example, the if
statement checks if the value of a
is greater than the value of b
, and since 5 is indeed greater than 3, the if
block is executed and "5 is greater than 3" is printed.
Quiz
- What is the value of the
is_raining
variable in the first example?- A)
True
- B)
False
- C)
"Bring an umbrella!"
- D)
"No need for an umbrella today."
- A)
-
What does the Boolean value
True
mean in Python?-
A) It represents a value that is the opposite of False
-
B) It represents a value that is the same as False
-
C) It represents a value that is a non-zero number
-
D) It represents a value that is the result of a successful comparison or operation
-
-
What does the Boolean value
False
mean in Python?-
A) It represents a value that is the opposite of True
-
B) It represents a value that is the same as True
-
C) It represents a value that is a non-zero number
-
D) It represents a value that is the result of an unsuccessful comparison or operation
-
-
Which of the following is NOT a valid Boolean value in Python?
-
A)
False
-
B)
0
-
C)
true
-
D)
None
-
-
Which of the following statements is true about Boolean values in Python?
-
A) The
bool
type can only represent two values:True
andFalse
-
B) The
bool
type can represent any non-zero number asTrue
-
C) The
bool
type can only represent two values:1
and0
-
D) The
bool
type can represent any value as eitherTrue
orFalse
-