Day 1.4 - CH4 - Flow Control
Day 1.4 - CH4 - Flow Control
ALGORITHMS WITH
PYTHON
3
CONDITIONS
4
Conditions usage examples
- ...
5
Python condition syntax
if expression:
# Code to execute if condition is True
Indented code # This part is indented with 4 spaces
#
else:
# Code to execute if condition if False
Indented code # This part is indented with 4 spaces
#
6
Condition example
print("Are you an adult ?")
age = int(input('Enter your age : ').strip())
7
Comparision operators
8
Comparision operators - example
if value == 42:
print("You have entered the number 42.")
else:
print("You have not entered the number 42.")
9
What are expressions
- Special rules:
- None which is a special value that represents nothing, evaluates to False.
- Any numerical value, float or int that is not 0 evaluates to True.
- Any str that is not empty evaluates to True.
- ...
10
Expressions examples
True # evaluates to True, this is a boolean
False # evaluates to False, this is a boolean
12
Logical tables - AND
The and operator makes the expression True if both values
evaluates to True.
13
Logical tables - OR
The or operator makes the expression True if at least one evaluates
to True.
14
Logical tables - NOT
The not operator reverses the value of the expression.
Value Result
True False
False True
15
Logical operators - example
min_quantity = 2
max_quantity = 5
16
If … else if … else
17
Python syntax for else if
if first_expression:
# Code executed if the first expression is True
# This part is indented with 4 spaces
elif second_expression:
# Code executed if the first expression is False
# And the second expression is True
# This part is indented with 4 spaces
else:
# Code to is executed if all expressions are False
# This part is indented with 4 spaces
18
If … elif ... else … - example
Second expression
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is 0")
19
Complex condition example
exam_score = float(input("Enter your exam score: "))
grade = "A"
elif exam_score >= 80:
grade = "B"
elif exam_score >= 70:
grade = "C"
elif exam_score >= 60:
grade = "D"
else:
grade = "F"
20
Loops
21
Usage
- Repeats the same instructions if
needed.
22
Loop iterations
23
Definite Iteration
- Iteration where we know how many loop to do before starting.
- Examples :
- Listing all values in a list.
- Getting all integer between a value x and a value y.
- Sending a notification to all users in a group.
- ...
24
"For" loop
- Logical structure that allows you to repeat an instruction.
- Usually used to iterate over collections or sequences.
- Included instructions must be indented.
25
For … in range(…)
- Uses the range() function for definite iteration.
- Will iterate over a sequence of integers defined by the given parameters
range(start, stop, step)
26
range(…) function examples
range start end step generates
range(5) Default=0 5 Default=1 [0, 1, 2, 3, 4]
range(10, 15) 10 15 Default=1 [10, 11, 12, 13, 14]
range(10, 15, 2) 10 15 2 [10, 12, 14]
range(5, 0, -1) 5 0 -1 [5, 4, 3, 2, 1]
range(10, step=2) Default=0 10 2 [0, 2, 4, 6, 8]
range(10, 2) 10 2 Default=1 [ ]
range(1) 0 1 1 [0]
27
for … in range(…) - example
# iterates over all integers between 0 and 5 included.
for i in range(0, 6, 1):
# i variable will take each value generated by range()
print(f"{i=}")
>>> i=0
>>> i=1
>>> i=2
>>> i=3
>>> i=4
>>> i=5
28
for … in range(…)
# Show the squared values of the integers between 0 & 5
for i in range(6):
squared = i ** 2
print(f"{i} * {i} = {squared}")
- Examples :
- Running a program until it receives a stop signal.
- Waiting until a player connects to a game server.
- Processing a video feed until the user disconnects.
- ...
30
While … loop
i = 0
- Used for indefinite iteration.
while i < 5:
print(f"{i=}")
i += 1
- Takes a boolean expression as the stop condition.
>>> "i=0"
>>> "i=1"
- Executes its code as long as its condition is True. >>> "i=2"
>>> "i=3"
>>> "i=4"
31
While … loop - example
terminate = False
while not terminate:
user_input = input("Do you want to quit? (y/n): ")
if user_input.lower() == "y":
terminate = True
print("Goodbye !")
33
Nested loop
35
Nested loops - example
>>> 1 * 1 = 1
>>> 1 * 2 = 2
for i in range(1, 11): >>> 1 * 3 = 3
# indented with 4 spaces >>> 1 * 4 = 4
for j in range(1, 11): >>> 1 * 5 = 5
# indented with 8 spaces (2 * 4) …
result = i * j >>> 10 * 8 = 80
print(f"{i} * {j} = {result}") >>> 10 * 9 = 90
>>> 10 * 10 = 100
36
The 'break' keyword
- Stop the current loop when encountered.
- Possible usages :
- Early termination during error handling.
- Iterating on a sequence until a specific value.
- Exiting a loop on a condition.
- ...
37
The 'break' keyword - example
while True:
user_input = input("Enter 'q' to quit: ")
if user_input == 'q':
print("Exiting the loop.")
break # break is encountered, we exit the loop
else:
print(f"You entered: {user_input}")
- Possible usages :
- Skip some values during iteration.
- Skip unwanted instructions depending on a condition.
- ...
39
The 'continue' keyword - example
40
do … while - loop
- Execute your instructions at least once.
- Sadly, not native to python, must use a trick to simulate it.
value = -1
while True:
input_value = input("Please enter an integer : ")
if input_value.isnumeric():
value = int(input_value)
break
print("Invalid value")
43
while … else - example
i = 0
end_loop = 5
44
Conclusion
- You can control the execution of code using conditions.
- You can repeat actions using loops.
- There are two types of iteration : definite & indefinite.
- You can stop loops using the break keyword.
- You can skip iterations using the continue keyword.
- It is possible to nest multiple logical structures.
45
Let’s practice !
46