CHAPTER 4.
LOOPS
Mariefel T. Basibas
Page 02
Chapter
4.1
Python
Loops For
Loops While
loops
The Break Statement
Continue Statement
Iterating with For Loop
Iterating with while Loop
Looping through an
Iterator
Python
Loop
In Python, looping
refers to the process of
executing a set of
statements repeatedly,
either for a specified
number of times or until
a particular condition is
met.
Python
Loop
There are two primary types of loops used in
Python:
For Loops: While Loops:
These are used for iterating over a With the while loop we
sequence (such as a list, tuple, dictionary,
can execute a set of
set, or string).
With a for loop, you can execute a set of statements as long as a
statements, once for each item in a list, condition is true.
tuple, etc.
Example
sample Codes
using for
loop
Outpu
With the for loop
t we can execute a
set of statements,
once for each item
in a list, tuple, set
sample Codes
Example
using while
loop
The while loop requires relevant
variables to be ready, in this example we
Outpu need to define an indexing variable, i,
t
which we set to 1
Note: remember to
increment i, or else the
loop will continue
forever.
sample Codes
Example
using while
loop
While Loops: These
Outpu execute a set of
t
statements as long as a
condition is true.
The break Sample code
Statement
With the break statement we
can stop the loop even if the
while condition is true:
Outpu
t
Exit the loop when i is 4.
The Sample code
Example: Skipping Even
Numbers
Continue
The continue statement in
Statement
Python is used to skip the rest
of the code inside a loop for
the current iteration only.
Loop does not terminate but
Outpu
continues on with the next
t
iteration. This statement can
be used in both for and while
loops.
Iterating with
a For Loop
Code Output
In this example, we use a for loop to
iterate through a list of numbers. For
each number, we check if it is even.
If it is, we print the number.
Iterating with
a For Loop
Code Output
For a while loop example, let's do
something slightly different. We'll
simulate a countdown from a
specified number, printing each
number until we reach 0.
Looping Through an
Iterator
We can also use a for loop to iterate through an iterable
object:
Example
Iterate the values of a tuple:
Iterate the characters of a
Example
string: