Bool type
Contents
10. Bool type#
Author: Tue Nguyen
10.1. Outline#
Why
booltype?How to get a
bool?Conversion to
boolWhen 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:
boolPossible values:
TrueandFalse
Note that Python is case-sensitive. Thus,
True,TRUE, andtrueare 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
bool0,None, and values considered as “empty” will produceFalseNone-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
ifstatement 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,
ifexpect abool, but it receives an empty listThus, Python converts this empty list to bool and ends up a
FalseSince the condition is
False, Python execute the statement underelse
10.5. When use bool?#
A
boolis normally used as the condition for branching in anifstatementWe will learn more about
iflater 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 >= 4producesTrue(since8 > 4)so Python executes the statements under
ifIf we change
8to3, thengrade >= 4will producesFalse, and Python will run the statements underelseLet’s confirm this
grade = 3
if grade >= 4:
print("Passed")
else:
print("Failed")
Failed
10.6. Operations on bool#
Since
booltype is also so simple, there are not much operationsHere is all you need to know
Logical operations
Since
boolis 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
Trueis equivalent to1Falseis 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
0and empty values will producesFalseNon-zero and non-empty values will produce
True
Sometimes Python does implicit type conversion to
boolas in anifstatement
How to get a bool?
From
TrueorFalseliteralsFrom an expression that produces a
boolsuch asComparison:
==, !=, >=, <=, >, <, is, is notTypecasting:
bool(x)Logical operations on
bools:(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,notOther math and logical operations when
boolvalues are treated asintvalues
10.8. Practice#
10.8.1. Exercise 1#
Do the following
Initialize a variable
xwith valueTruePrint the value associated with
xPrint the data type of
x
10.8.2. Exercise 2#
Do the following
Initialize a variable
xwith value10Initialize a variable
ywith a value from a comparison that checks whetherxis greater than5or notPrint the value associated with
yPrint the data type of
y
10.8.3. Exercise 3#
Do the following
Initialize a variable
xwith valueTrueInitialize a variable
ywith value100Check if
xis of typebool(Hint: type?isinstanceto see how you can use it)Similarly, check if
yis of typebool
10.8.4. Exercise 4#
Do the following
Initialize a variable
xwith value7Check if
xis 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
xwith an arbitrary valueIf
xis 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.5toxWhat happens?
What is your opinion?