Python Basics
Conditional Statements and Loops
Learning Objectives
By the end of this lesson, you will be able to:
Implement decision control structures in Python
Learn different types of loops in Python
Learn to implement loop control statements
Describe and use the range function in Python
Business Scenario
ABC is an e-commerce organization that deals with the listing of online products
based on their purchase, reviews, and availability. The users filter these products
based on multiple factors. The products are listed only if it matches a few criteria,
else an error is displayed.
The organization is supposed to develop this module with the help of control
structure, implement range functions to filter based on the ranges, and
implement looping control statements.
In this lesson, we will explore the following:
• Decision control structures in Python
• Loops, loop control structures, and loop-else statements in Python
Decision Control Structures in Python
Discussion
Decision Control Statements
How can decisions be made in Python?
• What is decision-making in Python?
• What are the types of decision-making statements and why they are
needed?
Decision Making
Decision-making is the process of making choices or performing tasks based on conditions.
Decision control structures evaluate variables or expressions that return either True or False as an outcome.
Start
Condition
Expression
Statement in Statement in
ifAction/ta
branch else branch
sk
Stop
Decision Control Structures: Scenario
Start
Rain
Rains
● Based on weather conditions, I can choose Condition tomorrow
my activities throughout the day. morning?
● IF it rains tomorrow morning, I will clean False
True
my room and do chores.
● ELSE, go swimming. Clean room and do
chores Swimming
Stop
Nested if Statements
The scenario is explained in the following flowchart:
No
Raining
Start Go swimming
tomorrow?
Yes
Tidy up the cellar and
Clean room and do paint the walls
chores
Swimming
Some
time left?No
Some time Stop
left?
Yes
Do my taxes Do tax declaration
Decision Control Structures
Four types of decision control structures are available in Python:
If-else
If statement statement
Control
structures in
Python
Nested-if If-elif-else
statement statement
If Statement
Python uses the if statement to change the flow of control in the program.
The indentation is used to mark the block of code.
Syntax
if condition: • A colon marks the beginning of the block of code.
statement • The block of code is indented, usually at four spaces.
statement • Each statement in the block of code should be at the same
……. indentation.
If Statement: Example
The following example illustrates the use of the if statement.
Example
If-Else Statement
The if-else statement evaluates the condition and executes the body of if only when the
test condition is True. Otherwise, the body of the else block will be executed.
Syntax
if condition:
statement 1
statement 2
else:
statement 3
statement 4
The else statement is an optional statement in the if-else construct.
If-Else Statement: Example
The following example illustrates the use of the if-else statement.
Example
If-Elif-Else Statement
The if-elif-else statement allows checking for multiple conditions. If the condition
for if is False, it checks the condition of the next elif block and so on.
Syntax
if condition 1:
statement
elif condition 2:
statement
elif condition 3:
statement
else:
statement
Only one block among the several if-elif-else blocks is executed according to the condition.
If all the conditions are False, the body of else is executed.
If-Elif-Else Statement: Example
The following example illustrates the use of the if-elif-else statement.
Example
Nested-If
Python allows an if statement inside another if statement.
Syntax
if (condition 1):
statement
• This format is called nesting in programming.
# Executes when condition 1 is True
if (condition 2): • The level of nesting is defined by using
# Executes when condition 2 is also True indentation.
# inner if Block ends here
# outer if Block ends here
Nested-If: Example
The following example illustrates the use of the nested-if statement.
Example
True or False
Python evaluates the following objects as False:
• Numerical zero values
• Boolean value False
• Empty strings
• Empty list, tuples, and dictionaries
• None
All other values are considered True in Python.
Decision Control Statements
How can decisions be made in Python?
• What is decision-making in Python?
Answer: Decision-making is the process of making choices or performing
tasks based on conditions. Decision control structures and evaluate variables
or expressions that return either True or False as an outcome.
• What are the types of decision-making statements and why are
they needed?
Answer: The different decision-making statements are the If statement, If-
else statement, If-elif-else statement, and nested-if statement.
Loops
Discussion
Loops
Are decision-making statements and loops the same?
• What are loops in Python?
• Identify the types of loops
Loops
A loop statement allows the execution of a statement or group of statements multiple times.
Start
Tidy up the cellar and
paint the walls
Condition End
Swimming
Some
time left?
True
Execute Statement
Do tax declaration
Types of Loops
The following types of loops are used to handle looping requirements.
Count Condition Collection
controlled loop controlled loop controlled loop
Count Controlled Loop
A method of repeating a loop a predetermined number of times
Syntax
for <num> in <range>:
body of loop
Condition Controlled Loop
A loop will be repeated until a given condition changes True to False or False to
True, depending on the type of loop.
Syntax
while <condition is true>:
body of loop
Collection Controlled Loop
This is a special construct that allows looping through the elements of a
“collection,” which can be an array, list, or other ordered sequences.
Syntax
for <item> in <list>:
body of loop
Loops in Python
Python supports for and while loop.
Start Start
Tidy up the Tidy up the
cellar and False
cellar and
Yespaint the walls
paint the walls
Last item Exit loop
reached? Condition Exit loop
Swimm Swimm
ing ing
No True
Execute Execute
Statement Do tax Statement Do tax
declaration declaration
For loop While loop
Loops in Python
Python supports for loop and while loop.
for loop while loop
The for loop is used to iterate over a The while loop is used to iterate over a
sequence list, tuple, string, or other block of code if the test expression is
objects. Its syntax is: true. Its syntax is:
for a in iteration_object: while test_expression:
Body Body
of of
loop loop
Loops in Python: Example
The following examples illustrate the use of for and while loops.
for loop while loop
Nested Loops
A nested loop is a loop inside the body of the outer loop.
Syntax
The inner and outer loops can be of the different or the same type.
Nested Loops: Flowchart
A nested loop is demonstrated in the following flowchart.
for each element
in the sequence
Yes Yes
Is this the last
element of
outer loop?
End of outer No
loop
Is this the last
element of
inner loop?
No
No
Inner loop
statements
Nested Loops: Example
The following example illustrates the use of the nested loop.
Code to print multiplication table from 2 to 10
Loops
Are decision-making statements and loops the same?
• What are loops in Python?
Answer: A loop statement allows the execution of a statement or group of
statements multiple times.
• Identify the types of loops
Answer: The types of loops include the count-controlled loop, the condition-
controlled loop, and the collection-controlled loop.
Loops Control Statements
Discussion
Loop Control Statements
• What is the difference between break and continue?
• Give an example or scenario where break and continue can be used.
Loops Control Statements
Loop control statements change the flow of execution in loops.
Python supports two such statements.
break Loop control
continue
statements
Loops Control Statements: Break
Syntax
• The break statement breaks the
innermost enclosing of for or while
break loop.
• It terminates the nearest enclosing loop
and skips the optional else.
• If a loop is terminated by a break, the
loop variable keeps its current value.
Break: Example
The following example illustrates the use of a break statement.
Example
Loops Control Statements: Continue
Syntax
• The continue statement skips the
current iteration and continues with the
next iteration.
continue • It does not terminate the loop; it just
moves the control to the next iteration.
• Since the loop does not terminate
unexpectedly, it executes the optional
else block of the loop.
Continue: Example
The following example illustrates the use of the continue statement.
Example
Loop Control Statements
• What is the difference between break and continue?
Answer: The break statement breaks the innermost enclosing of for or while
loop, whereas the continue statement skips the current iteration and
continues with the next.
• Give an example or scenario to define where each of them can be used.
Answer: In case the optional else has to be used, the continue statement can
be used as it executes the optional else block of the loop, whereas, in another
case, the break statement can be used.
Loop Else Statements
Loop Else Statement
Python allows the else The statements of the else
keyword to be used with block are executed after all
both the for and while the iterations are
loops. Plan completed.
The program exits the loop
Else clause is defined after the
only after the else block is
body of the loop.
executed.
Loop Else Statement
The loop else statement is not executed when the loop is terminated because
of a break statement.
Normal Loop Loop with Else
Start Start
False Exit False Execute else
Condition Condition
Loop statement
True True
Execute statement Execute statement
For Else Statement: Example
The following example illustrates the use of a for else statement.
Example
While Else Statement: Example
The following example illustrates the use of a while else statement.
Example
Range Function
The built-in function range can be used with loops to iterate over a sequence of numbers. It
generates an iterator of arithmetic progressions.
range(n) range()
range(start, stop)
syntax
The range object can be converted to a sequence collection using a function
such as list and tuples.
Range(n) Function
It generates a sequence of n integer numbers starting from 0 and ending with (n-1).
Example
Range(start, stop) Function
It generates a sequence of integer numbers starting with the start value and ending
with (stop-1).
Example
Step in Range
The range() function has an additional optional step argument that specifies the increment of the
sequence.
Syntax
range(start, stop, step)
The default increment value is 1. The increment value can be positive or negative but
not zero.
Step in Range: Example
Positive step value creates a forward Negative step value creates a reverse
sequence. sequence.
Example Example
Key Takeaways
If-else conditional constructs are used to control the program's flow.
For and while loops are used to repeatedly execute statements.
The break and continue statements are used to skip some statements
inside the loop or terminate the loop immediately without checking the
condition.
Python supports the else clause with for and while loops.
Range function in Python is used to generate a range of numbers
and it also works with for loop.
Knowledge Check
Knowledge
Check
Which of the following is not used as a loop in Python?
1
A. for loop
B. while loop
C. do-while loop
D. None of the above
Knowledge
Check
Which of the following is not used as a loop in Python?
1
A. for loop
B. while loop
C. do-while loop
D. None of the above
The correct answer is C
Python does not use the do-while as a loop.
Knowledge
Check
Which one of the following is a valid Python if statement?
2
A. if a>=2 :
B. if (a>=2)
C. if a>=22
D. if a=>22
Knowledge
Check
Which one of the following is a valid Python if statement?
2
A. if a>=2 :
B. if (a>=2)
C. if a>=22
D. if a=>22
The correct answer is A
In Python, an if statement always ends with a colon.
Knowledge
Check
Where can the continue statement be used?
3
A. while loop
B. for loop
C. do-while loop
D. Both A and B
Knowledge
Check
Where can the continue statement be used?
3
A. while loop
B. for loop
C. do-while loop
D. Both A and B
The correct answer is D
The continue statement can be used in both while and for loops.