Module 03. Control Flow
Lecture Date: September 8, 2021 - Wednesday Slides
DataCamp Chapter: Intermedia Python
-> Logic, Control Flow and Filtering
In this lecture, we will delve into comparisons, conditional statements, and logic. In fact, these topics are fundamental programming concepts that can be useful in a variety of applications. More specifically, we will learn comparison operations such as ==
which means equal to
. It will be followed by logic operators such as not
, or
. Finally, we will learn if
, elif
, and nested if
statements as part of this module.
1. Control Flow
1.1. Comparisons
-5 == 5
False
the above code returns False
because -5 and 5 are not equal. If they were equal, then, the result would be True
. Both False
and True
are bool type variables as shown below.
comparison_result = -5 == 5
type(comparison_result)
bool
Operator | Meaning |
---|---|
== | equal to |
!= | not equal to |
> | greater than |
>= | greater than or equal to |
< | less than |
<= | less than or equal to |
3 >= 2.718281828459045 # e number
True
Python Tip: =
and ==
operators have different meanings. While x=5
assigns x variable a value, x==5
compares x with 5.
x=5
x==5
True
Python Tip: Recall that exact floating point arithmetic is NOT possible in Python.
a = 0.1
b = 0.2
c = a + b
print(c == 0.3)
False
1.2. Logic Operators
not 4 > 2
False
1 == 1 and 4 > 2
True
import math
math.pi > math.e or 1 < 2
True
Truth table for not
operator
P | not P |
---|---|
False | True |
True | False |
Truth table for and
operator
P | Q | P and Q |
---|---|---|
False | False | False |
False | True | False |
True | False | False |
True | True | True |
Truth table for or
operator
P | Q | P or Q |
---|---|---|
False | False | False |
False | True | True |
True | False | True |
True | True | True |
not 5 > 3 and 6 + 1 > 7
False
3 * 5 < 15 or math.sqrt(4) == 2
True
not 4 > 3.99999 or 5 % 2 == 1
True
not (4 > 3.99999 or 5 % 2 == 1)
False
not 4 > 3.99999 and 5 % 2 == 1
False
1.2.1. Detailed rules
int(5.4)
bool(0)
bool(0.0)
bool(complex(0,0))
bool(9999)
bool(-9999)
bool(0.00000001)
bool(complex(0,1))
bool(None)
bool(not None)
not not bool(None)
x = None
print (x is None)
x = 4
print (x is None)
1.3. Conditional Statements
x = 5
y = 7
if x < 5:
print('X is less than 5')
elif x >=5 and y < 10:
print('x is greater than or equal to 5, but y is less than 10')
else:
print('Neither of the two above conditions hold')
x = 5
y = 7
z = None
if x < 5:
print('X is less than 5')
elif x >=5 and y < 10:
print('x is greater than or equal to 5, but y is less than 10')
if z is None:
print('z is None')
else:
print('Neither of the two above conditions hold')
x is greater than or equal to 5, but y is less than 10
z is None