Python - Loops

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Introduction to Business Analytics

Copyright © LEARNXT
Introduction to Python Programming

Loops in Python
Copyright © LEARNXT
Objectives
At the end of this topic, you will be able to understand and explain:
 Understand the basics of loops in Python

 Explain for and while loop statements with examples

 Explain the usage of break and continue statements

 Explain how to setup flow control within loops

Copyright © LEARNXT
Loops in Python
Copyright © LEARNXT
Python Loops
 A loop statement allows us to execute a statement or group of statements multiple times

 Statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on

 A block of code may get executed several number of times

Conditional Code

If condition
is true
condition

If condition
is false

Copyright © LEARNXT
Types of Loops

Types of Loops

while Loop
for Loop
Run as long as a specific
Run a set number of times
logical condition is true

Copyright © LEARNXT
for and while Loops
Copyright © LEARNXT
for Loop Statement
 Definition: The for loop executes a sequence of statements multiple times and abbreviates the
code that manages the loop variable

 Syntax:

 for iter in sequence:

 statements(iter)

Copyright © LEARNXT
for Loop - Flowchart

For each element


In the sequence

Yes
Is this the last
element of
the
sequence?

No

Statements
End of ‘for’ loop
inside ‘for’ loop

Copyright © LEARNXT
Example I - for Loop Using a Range
 for i in range(5):

 print("Hello Python")

 Hello Python

 Hello Python

 Hello Python

 Hello Python

 Hello Python

Copyright © LEARNXT
Example II: for Loop Using a List
 list1 = [25, 50, 75]

 print(list1)

 [25, 50, 75]

 for num in list1:

 print(“num is equal to: ”, num)

 num is equal to: 25

 num is equal to: 50

 num is equal to: 75

Copyright © LEARNXT
Example III: for Loop Using a String
 for letter in "Gabby":

 print(f“ looping over letters in name: {letter}")

 looping over letters in name: G

 looping over letters in name: a

 looping over letters in name: b

 looping over letters in name: b

 looping over letters in name: y

Copyright © LEARNXT
while Loop Statement
 Definition:

 A while loop statement in Python repeatedly executes a target statement as long as a given
condition is true

 A while loop is a type of loop that runs as long as a logical condition is True

 When the logical condition becomes False, the loop stops running

 Syntax:

 while <logical_condition>:

 <code>

Copyright © LEARNXT
while Loop - Flowchart

Start of the loop

False

Condition

True

Statements or
Exit the loop
body of while

Copyright © LEARNXT
while Loop - Example
 i=1

 print(i)

 while i < 3:

 print(i)

 i=i+1

 1

 1

 2

Copyright © LEARNXT
break and continue Statements
Copyright © LEARNXT
Break and Continue Statements
 In Python, break and continue statements can alter the flow of a normal loop

 Loops iterate over a block of code until the test expression is false, but sometimes we wish to
terminate the current iteration or even the whole loop without checking test expression

 The break and continue statements are used in these cases

Copyright © LEARNXT
break Statement
 Definition:

 The break statement terminates the loop containing it. Control of the program flows to the
statement immediately after the body of the loop

 If the break statement is inside a nested loop (loop inside another loop), the break statement
will terminate the innermost loop

 Syntax:

 break

Copyright © LEARNXT
break - Flowchart
Enter loop

test expression False


of loop

True

Yes
break?

No
Exit Loop
Remaining body
of loop

Copyright © LEARNXT
break - Example
 for val in "string":

 if val == "i":

 break # Use of break statement inside the loop

 print(val)

 print("The end")

 s

 t

 r

 The end
Copyright © LEARNXT
continue Statement
 Definition:

 The continue statement is used to skip the rest of the code inside a loop for the current
iteration only

 Loop does not terminate but continues on with the next iteration

 Syntax:

 continue

Copyright © LEARNXT
continue - Flowchart

Enter loop
test expression False
of loop

True

Yes
Continue?

No
Exit Loop
Remaining body
of loop

Copyright © LEARNXT
continue - Example
 for val in "string":

 if val == "i": # Program to show the use of continue statement inside loops

 continue

 print(val)

 print("The end")

s
t
r
n
g
The end

Copyright © LEARNXT
Flow Control Within Loops
Copyright © LEARNXT
Flow Controls Within Loops
 General structure of a loop:

 while <statement> (or for <item> in <object>):

 <statements within loop>

 if <test1>: break # exit loop now

 if <test2>: continue # go to top of loop now

 if <test3>: pass # does nothing!

 else:

 <other statements> # if exited loop without hitting a break

Copyright © LEARNXT
Using the “loop else”
 An else statement after a loop is useful for taking care of a case where an item isn't found in a
list

 for i in range(3):

 if i == 4:

 print("I found 4!“)

 break
Don't care about 0
 else:
Don't care about 1
 print ("Don't care about“,i)
Don't care about 2
 else: I searched but never found 4!

 print ("I searched but never found 4!“)


Copyright © LEARNXT
for ... in: Example
 for name in ["Mutasim", "Micah", "Ryan"]:

 if name[0] == "M":

 print(name, "starts with an M")

 else:

 print(name, "doesn't start with M")

 Mutasim starts with an M

 Micah starts with an M

 Ryan doesn't start with M

Copyright © LEARNXT
Summary
 A loop statement allows us to execute a statement or group of statements multiple times

 Statements are executed sequentially: The first statement in a function is executed first,
followed by the second, and so on

 Two basic types of loops: for and while loops

 for loop executes a sequence of statements multiple times and abbreviates the code that
manages the loop variable

 while loop repeatedly executes a target statement as long as a given condition is true

 In Python, break and continue statements can alter the flow of a normal loop

Copyright © LEARNXT
Additional Resources
 McKinney, W. (2013). Python for data analysis. O'Reilly Media.

 Lutz, M. (2013). Learning Python: Powerful object-oriented programming. O'Reilly Media.

 Summerfield, M. (2010). Programming in Python 3: A complete introduction to the Python


language. Pearson Education India.

 Matthes, E. (2019). Python crash course: A hands-on, project-based introduction to


programming (2nd ed.). No Starch Press.

 Beazley, D., & Jones, B. K. (2013). Python cookbook: Recipes for mastering Python 3. O'Reilly
Media.

Copyright © LEARNXT
e-References
 Welcome to Python.org. (n.d.). Python.org. https://www.python.org

 Introduction to Python. (n.d.). W3Schools Online Web


Tutorials. https://www.w3schools.com/python/python_intro.asp

Copyright © LEARNXT 30
Any Questions?

Thank you
Copyright © LEARNXT
Copyright © LEARNXT

You might also like