0% found this document useful (0 votes)
30 views46 pages

Day 1.4 - CH4 - Flow Control

Uploaded by

nguejip47
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views46 pages

Day 1.4 - CH4 - Flow Control

Uploaded by

nguejip47
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 46

1ALG

ALGORITHMS WITH
PYTHON

Chapter 4: Flow control


Summary
- Conditions.
- Definite iterations.
- Indefinite iterations.
- Nested loops.
- Loop control keywords.
Conditions

3
CONDITIONS

Logical structure that does something


depending on an expression.

4
Conditions usage examples

- Checking if a number is positive.

- Acting depending on a user action.

- Redirecting a user if it is logged in.

- Doing something if a user has the required permission.

- Processing a payment if the account balance is valid.

- ...

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())

if age >= 18:


# Code to execute if condition is True
print("You are an adult !")
else:
# Code to execute if condition if False
print("You are a minor !")

7
Comparision operators

Operator Name Example


== Equal 1 == 1
!= Not equal 1 != 2
< Less than 1<2
> Greater than 2>1
<= Less than or equal 1<= 2
>= Greater than or equal 2 >= 2

8
Comparision operators - example

value = int(input("Enter an integer number : "))

if value == 42:
print("You have entered the number 42.")
else:
print("You have not entered the number 42.")

9
What are expressions

- Something that can be evaluated to a boolean value (True / False).

- 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

None # evaluates to False, this means that there is nothing

2000 # evaluates to True, all number that is not 0 evaluates to True


2000.2 # evaluates to True
0 # evaluates to False
0.0 # also evaluates to False

42 > 41 # this comparision is True


-4 > 4 # this comparision is False

True == False # this is False


11
Logical operators

- Used to create complex expressions by combining other expressions.

Operator Description Example


and Returns True if both are True. True and False => False
or Returns True if at least one is True. True or False => True
not Reverse the boolean value not True => False

12
Logical tables - AND
The and operator makes the expression True if both values
evaluates to True.

First value Second value Result


True True True
True False False
False True False
False False False

13
Logical tables - OR
The or operator makes the expression True if at least one evaluates
to True.

First value Second value Result


True True True
True False True
False True True
False False False

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

wanted_quantity = int(input("Enter the quantity that you want : ").strip())

if min_quantity <= wanted_quantity and wanted_quantity <= max_quantity:


print("You can proceed with this quantity")
else:
print(f"Quantity must be between {min_quantity} and {max_quantity}.")

16
If … else if … else

Conditions are sometimes more complex than a


simple if ... else

In the example we check if a number is positive,


negative or zero.

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

x = float(input("Enter a value for x : ").strip())


First expression

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: "))

if exam_score >= 90:


Conditions execution order

grade = "A"
elif exam_score >= 80:
grade = "B"
elif exam_score >= 70:
grade = "C"
elif exam_score >= 60:
grade = "D"
else:
grade = "F"

print(f"Your grade is {grade}")

20
Loops
21
Usage
- Repeats the same instructions if
needed.

- Two types of loops in python : for &


while

22
Loop iterations

Definite : we know before starting how many loops we will do.

Indefinite : when we stop looping depends on a condition.

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.

for something in iterator:


# indented with 4 spaces
# here are the instructions to execute
#

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)

Parameter Description Default


start Starting integer of the sequence. 0
stop Integer at which the sequence stops (not included). mandatory
step Value to increment. 1

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}")

>>> "0 * 0 = 0"


>>> "1 * 1 = 1"
>>> "2 * 2 = 4"
>>> "3 * 3 = 9"
>>> "4 * 4 = 16"
>>> "5 * 5 = 25"
29
Indefinite Iteration

- Iteration where how many loops we do depends on a condition.

- 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 !")

>>> Do you want to quit? (y/n): n


>>> Do you want to quit? (y/n): n
>>> Do you want to quit? (y/n): y
Goodbye !
32
Infinite loop
i = 0
- A loop that never ends. while i <= 10:
print(f"i is {i}")
i -= 1
- Your program will never finish.
>>> "i is 0"
- Can lead to many issues : >>> "i is -1"
>>> "i is -2"
- increased CPU usage >>> "i is -3"
- memory leaks >>> "i is –4"
>>> "i is -5"
- ... ...

33
Nested loop

- You can include loops inside of other loops


- You can include any logical structure inside another

- Each new layer news another level of indentation.

- Be careful of cognitive load :


- too much nested structures are hard to understand !
34
Nested loops - example

for i in range(1, 11):


# indented with 4 spaces
for j in range(1, 11):
First loop body. # indented with 8 spaces (2 * 4)
result = i * j Second loop body.
print(f"{i} * {j} = {result}")

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}")

>>> Enter 'q' to quit: no


>>> You entered: no
>>> Enter 'q' to quit: q
>>>Exiting the loop.
38
The 'continue' keyword
- Skip the remaining instructions and go to the next iteration.

- Possible usages :
- Skip some values during iteration.
- Skip unwanted instructions depending on a condition.
- ...

39
The 'continue' keyword - example

# display numbers between 0 and 10


>>> i=1
# but skips multiples of 3
>>> i=2
for i in range(1, 11):
>>> i=4
if i % 3 == 0:
>>> i=5
# modulo can be used to detect multiples
>>> i=7
continue
>>> i=8
print(f"{i=}")
>>> i=10

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")

print(f"You entered {value=}")


41
Loop … else ...
Executes instructions if the loop has naturally ended.
42
for .. else … - example
# check for multiples of 15 in a given range
start = int(input("Enter the start of the range : "))
end = int(input("Enter the end of the range : "))

for i in range(start, end + 1):


if i % 15 == 0:
print(f"Found a multiple of 15 in the range : {i}")
break
else:
print("There are no multiple of 15 in the range.")

43
while … else - example
i = 0
end_loop = 5

while i < end_loop:


print(f"There are {end_loop - i} iteration(s) remaining.")
want_to_stop = input("Do you want to stop the loop (y/n) ? : ")
if want_to_stop == "y":
break
i += 1
else:
print("You have finished the loop without stopping early!")

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

You might also like