2 Control Flow
2 Control Flow
➢ conditional statements;
➢ loops;
➢ function calls.
1. Comparison Operators
Operator Meaning
== Equal to
!= Not equal to
➢ These operators evaluate to True or False depending on the values you give them.
Examples:
>>> 42 == 42 True
>>> 40 == 42 False
>>> 42 == '42'False
2. Boolean Operators
Expression Evaluates to
Expression Evaluates to
Expression Evaluates to
3. Mixing Operators
>>> (1 == 2) or (2 == 2) True
➢ Also, you can mix use multiple Boolean operators in an expression, along with
the comparison operators:
4. if Statements
➢ The else statement executes only if the evaluation of the if and all the elif
expressions are False:
print('Hi, George.')
else:
➢ Only after the if statement expression is False, the elif statement is evaluated
and executed:
print('Hi Debora!')
print('Hi Debora!')
print('Hi George!')
else:
➢ Example:
>>> age = 15
print('kid')
else:
>>> age = 15
>>> print('kid' if age < 13 else 'teen' if age < 18 else 'adult')
print('kid')
else:
print('teen')
else:
6. Switch-Case Statement
➢ Switch-Case statements
Official Tutorial
The PEP 636 provides an official tutorial for the Python Pattern matching or
Switch-Case statements.
... print("OK")
... print("Created")
# Created
In this example, the pipe character (| or or) allows python to return the same response
for two or more cases.
... print("OK")
... print("Redirect")
Default value
... print("OK")
... print("Redirect")
... case _:
... case _:
>>> spam = 0
# Hello, world.
# Hello, world.
# Hello, world.
# Hello, world.
8. break Statements
➢ If the execution reaches a break statement, it immediately exits the while loop’s
clause:
9. continue Statements
... continue
... break...
Charles
Debora
# Access granted.
10. For loop
➢ The for loop iterates over a list, tuple, dictionary, set or string:
... print(pet)
The range() function can also modify it’s 3 defaults arguments. The first two will be
the start and stop values, and the third will be the step argument. The step is the
amount that the variable is increased by after each iteration.
):... print(i)...
# 0# 2# 4# 6# 8
You can even use a negative number for the step argument to make the for loop count
down instead of up.
... print(i)...
# 5# 4# 3# 2# 1# 0
This allows to specify a statement to execute in case of the full loop has been
executed. Only useful when a break condition can occur in the loop:
... if i == 3:
... break
... else: