Bool type
Contents
10. Bool type#
Author: Tue Nguyen
10.1. Outline#
Why
bool
type?How to get a
bool
?Conversion to
bool
When uses
bool
?Operations on
bool
10.2. Why bool
type?#
Motivation: used to represent binary data
Real-life data: True/False, Yes/No, Success/Failure, Male/Female, Good/Bad
Python implementation:
Type:
bool
Possible values:
True
andFalse
Note that Python is case-sensitive. Thus,
True
,TRUE
, andtrue
are different
10.3. How to get a bool
?#
a) Ex 1: from True
and False
literals
# Init two bool variables
x = True
y = False
# Print values
print(x)
print(y)
True
False
# Print types
print(type(x))
print(type(y))
<class 'bool'>
<class 'bool'>
b) Ex 2: from an expression that produces a bool
A bool
is often produced from
A comparison
A call to a function that returns a
bool
b1) Get a bool
from a comparison
# Init two variable
x = 1000
y = 2000
# Check equal
x == y
False
# Check NOT equal
x != y
True
# Another way to check NOT equal
not(x == y)
True
# Check if IDs are the same
x is y
False
# Check if IDs are NOT the same
x is not y
True
# Check greater than
x > y
False
# Check greater than or equal
x >= y
False
# Check less than
x < y
True
# Check less than ro equal
x <= y
True
b2) Get a bool
from a function call
# Init 2 strings
s1 = "Hello"
s2 = "HELLO"
# Check if all chacters in s1 are uppercase
s1.isupper()
False
# Check if all chacters in s2 are uppercase
s2.isupper()
True
10.4. Conversion to bool
#
Type conversion is the action of converting a value of one type to a different type
Other names: typecasting,type-coercion
Think of it as converting USD to Euro
To convert a value to
bool
, we usebool()
function.Some rules to remember when converting a value of another type to
bool
0
,None
, and values considered as “empty” will produceFalse
None-zero and non-empty values will produce
True
a) Ex 1: from NoneType
bool(None)
False
b) Ex 2: from int
bool(0)
False
bool(100)
True
bool(-20)
True
c) Ex 3: from float
bool(0.0)
False
bool(1.5)
True
bool(1.2)
True
d) Ex 4: from collections
# Empty list
bool([])
False
# Empty dict
bool({})
False
# Empty string
bool("")
False
# Non-empty list
bool([1, 2, 3])
True
# Non-empty dict
bool({"name": "John", "age": 20})
True
# Non-empty string
bool("hello")
True
e) Ex 5: implicit typecasting
Python sometimes does this conversion implicitly
Ex: in a
if
statement where it expects a bool value to make a decisionConsider the following example
students = []
if students:
print("There is at least 1 student")
else:
print("There is no student")
There is no student
What happened?
Here,
if
expect abool
, but it receives an empty listThus, Python converts this empty list to bool and ends up a
False
Since the condition is
False
, Python execute the statement underelse
10.5. When use bool
?#
A
bool
is normally used as the condition for branching in anif
statementWe will learn more about
if
later in the “Control flows” sectionsFor now, consider the following simple example
grade = 8
if grade >= 4:
print("Passed")
else:
print("Failed")
Passed
What happened?
As you can see,
"Passed"
was printed out becausegrade >= 4
producesTrue
(since8 > 4
)so Python executes the statements under
if
If we change
8
to3
, thengrade >= 4
will producesFalse
, and Python will run the statements underelse
Let’s confirm this
grade = 3
if grade >= 4:
print("Passed")
else:
print("Failed")
Failed
10.6. Operations on bool
#
Since
bool
type is also so simple, there are not much operationsHere is all you need to know
Logical operations
Since
bool
is a sub-type ofint
, we can also performMath operations
Comparison operations
a) Ex 1: logical operations
There are 2 logical operators: and
, or
, not
a1) Simple examples on bool
literals
True and True
True
True and False
False
True or True
True
True or False
True
not True
False
not False
True
a2) More interesting examples on bool
expression
# Init 2 variables
age = 18
health = "bad"
# Rule 1: if age >= 18 AND good health, then you can buy a vodka
if (age >= 18) and (health == "good"):
print("Congrats. You can buy a vodka")
else:
print("Sorry. You cannot buy a vodka")
Sorry. You cannot buy a vodka
# Rule 2: if age >= 18 OR good health, then you can buy a vodka
if (age >= 18) or (health == "good"):
print("Congrats. You can buy a vodka")
else:
print("Sorry. You cannot buy a vodka")
Congrats. You can buy a vodka
b) Ex 2: treat bool
values as integers
Remember
True
is equivalent to1
False
is equivalent to0
# True + True
True + True
2
# True + False
True + False
1
# True > False
True > False
True
10.7. Summary#
Why bool
type?
Used to represent binary data
Used as conditions in branching statements
Conversion to bool
Use
bool()
Rules
0
and empty values will producesFalse
Non-zero and non-empty values will produce
True
Sometimes Python does implicit type conversion to
bool
as in anif
statement
How to get a bool
?
From
True
orFalse
literalsFrom an expression that produces a
bool
such asComparison:
==, !=, >=, <=, >, <, is, is not
Typecasting:
bool(x)
Logical operations on
bool
s:(age >= 18) and (health == "good"
A call to a function that returns a
bool
:x.isupper()
,isinstance(x, float)
When uses bool
?
When representing binary data
As conditions in branching statements
Operations on bool
Logical operations:
and
,or
,not
Other math and logical operations when
bool
values are treated asint
values
10.8. Practice#
10.8.1. Exercise 1#
Do the following
Initialize a variable
x
with valueTrue
Print the value associated with
x
Print the data type of
x
10.8.2. Exercise 2#
Do the following
Initialize a variable
x
with value10
Initialize a variable
y
with a value from a comparison that checks whetherx
is greater than5
or notPrint the value associated with
y
Print the data type of
y
10.8.3. Exercise 3#
Do the following
Initialize a variable
x
with valueTrue
Initialize a variable
y
with value100
Check if
x
is of typebool
(Hint: type?isinstance
to see how you can use it)Similarly, check if
y
is of typebool
10.8.4. Exercise 4#
Do the following
Initialize a variable
x
with value7
Check if
x
is greater than or equal to5
. If true, print"Above average"
. Otherwise, print"Below average"
.
10.8.5. Exercise 5#
Replicate Ex 4, but this time, use not
10.8.6. Exercise 6#
Give three typecasting examples that produce True
and three others that produce False
.
10.8.7. Exercise 7#
Do the following
Initialize a variable
x
with an arbitrary valueIf
x
is even, print"Even"
. Otherwise, print"Odd"
Try your code with different values of
x
10.8.8. Exercise 8#
Do the following
Replicate Ex 7, but this time assign
5.5
tox
What happens?
What is your opinion?