You are on page 1of 10

CHAPTER 4

ITERATION
NOEL B. ATAZAR
Teacher 1
Dr. Emilio B. Espinosa, Sr. Memorial State College of Agriculture and Technology
(DEBESMSCAT)
College of Arts and Sciences

Loops are blocks of code that keep repeating the same instructions until a certain condition is
met. We also use loops to access the different items in a given sequence and iterate them over
the sequence. Loops are a fundamental concept in any programming language. Repetitive tasks
are common in programming, so loops help save time and reduce errors.

Iteration - Most useful and powerful structure. Allows the repetition of instructions or
statements in the loop body.

Parts of the iteration structures:


 Loop body instruction(s) or statements which are repeated
 Loop-exit condition the condition to be tested before each repetition

Types:
 while loop
 for loop
o In
o Range

When to use the while loop and the for loop


 Loops that are dependent on a sentinel value (or indicator) are better coded using a while
loop
 The for loop is generally used for traversing and manipulating arrays
 When the number of times that the loop will be executed is known, the for loop provides
a convenient shorthand.

Common Loop Applications


1. Using a loop to accumulate totals

 An accumulator is a variable that “sums up” or accumulates values


 It is similar to a counter whose values change each time the loop is entered.
Counters, however, add a fixed value while accumulators accumulate
undetermined values.
2. Using a loop to validate user entry
 Data entered by a user usually needs validation. It needs to be checked for errors.
Incorrect data can lead to unwanted results and could end a program abnormally
 Usual checks for data are:
o If it is the correct data type
o For numeric data, if it is within an acceptable range of values

Chapter 4: Iteration
Lesson 4.1 While Loop Iteration

What is while loop in Python?

The while loop in Python is used to iterate over a block of code as long as the test expression
(condition) is true.

We generally use this loop when we don't know the number of times to iterate beforehand.

Syntax for while Loop in Python

while test_expression:
Body of while

Flowchart of while loop


Loop
In the while loop, test expression is checked first. The body of the
loop is entered only if the test_expression evaluates to True. After
one iteration, the test expression is checked again. This process
continues until the test_expression evaluates to False.

In Python, the body of the while loop is determined through


indentation. The body starts with indentation and the first
unindented line marks the end. Python interprets any non-zero value
as True. None and 0 are interpreted as False.

If the condition is initially false, the loop body will not be executed
at all.

Example: Python while loop

Chapter 4: Iteration
When you run the program, the output will be:

In the above program, the test expression will be True as long as our counter variable i is less
than or equal to n (10 in our program). We need to increase the value of the counter variable in
the body of the loop. This is very important (and mostly forgotten). Failing to do so will result in
an infinite loop (never-ending loop).

Finally, the result is displayed.

While loop with else

Same as with for loops, while loops can also have an optional else block. The else part is
executed if the condition in the while loop evaluates to False. The while loop can be terminated
with a break statement. In such cases, the else part is ignored. Hence, a while loop's else part
runs if no break occurs and the condition is false.

Here is an example to illustrate this.

Output:

Here, we use a counter variable to print the string Inside loop three times. On the fourth iteration,
the condition in while becomes False. Hence, the else part is executed.

Chapter 4: Iteration
Lesson 4.2 For Loop Iteration

When do I use for loops?

for loops are used when you have a block of code which you want to repeat a fixed number of
times. The for-loop is always used in combination with an iterable object, like a list or a range.
The Python for statement iterates over the members of a sequence in order, executing the block
each time. Contrast the for statement with the ''while'' loop, used when a condition needs to be
checked each iteration or to repeat a block of code forever. For example:

For loop from 0 to 2, therefore running 3 times.

While loop from 1 to infinity, therefore running forever.

When running the above example, you can stop the program by pressing ctrl+c at the same time.
As you can see, these loop constructs serve different purposes. The for loop runs for a fixed
amount of times, while the while loop runs until the loop condition changes. In this example, the
condition is the boolean True which will never change, so it will run forever.

How do they work?

If you've done any programming before, you have undoubtedly come across a for loop or an
equivalent to it. Many languages have conditions in the syntax of their for loop, such as a
relational expression to determine if the loop is done, and an increment expression to determine
the next loop value.

In Python, this is controlled instead by generating the appropriate sequence. Basically, any object
with an iterable method can be used in a for loop. Even strings, despite not having an iterable
method - but we'll not get on to that here. Having an iterable method basically means that the
data can be presented in list form, where there are multiple values in an orderly fashion. You can
define your own iterables by creating an object with next() and iter() methods. This means that
you'll rarely be dealing with raw numbers when it comes to for loops in Python - great for just
about anyone!

Nested Loops
When you have a block of code you want to run x number of times, then a block of code within
that code which you want to run y number of times, you use what is known as a "nested loop". In
Python, these are heavily used whenever someone has a list of lists - an iterable object within an
iterable object.

Like the while loop, the for loop can be made to exit before the given object is finished. This is
done using the break statement, which will immediately drop out of the loop and continue

Chapter 4: Iteration
execution at the first statement after the block. You can also have an optional else clause, which
will run should the for loop exit cleanly - that is, without breaking.

For..Else

Strings as an iterable

Lists as an iterable

Loop over Lists of lists

A note on ‘range’

The ''range'' function is seen so often in for statements that you might think range is part of
the for syntax. It is not: it is a Python built-in function that returns a sequence following a
specific pattern (most often sequential integers), which thus meets the requirement of providing a
sequence for the for statement to iterate over. Since for can operate directly on sequences, there
is often no need to count. This is a common beginner construct (if they are coming from another
language with different loop syntax):

It can be replaced with this:

Chapter 4: Iteration
Lesson 4.3 Break, Continue, and Pass Statements

Break Statements

 force immediate termination of a loop, bypassing the conditional expression and any
remaining code in the body of the loop
 The loop is terminated and program control resumes at the next statement following the
loop

The break statement, like in C, breaks out of the innermost enclosing for or while loop. Loop
statements may have an else clause; it is executed when the loop terminates through
exhaustion of the iterable (with for) or when the condition becomes false (with while), but
not when the loop is terminated by a break statement.

This is exemplified by the following loop, which searches for prime numbers:

(Yes, this is the correct code. Look closely: the else clause belongs to the for loop, not the if
statement.) When used with a loop, the else clause has more in common with the else clause of a
try statement than it does with that of if statements: a try statement’s else clause runs when no
exception occurs, and a loop’s else clause runs when no break occurs.

Continue Statements

Continue statement is a loop control statement that forces to execute the next iteration of the
loop while skipping the rest of the code inside the loop for the current iteration only i.e. when
the continue statement is executed in the loop, the code inside the loop following the continue
statement will be skipped for the current iteration and the next iteration of the loop will begin.

Example: Continue statement in Python

Consider the situation when you need to write a program which prints the number from 1 to 10
and but not 6. It is specified that you have to do this using loop and only one loop is allowed to
use. Here comes the usage of continue statement. What we can do here is we can run a loop
from 1 to 10 and every time we have to compare the value of the iterator with 6. If it is equal to
6 we will use the continue statement to continue to the next iteration without printing anything
otherwise we will print the value.

Chapter 4: Iteration
Below is the implementation of the above idea:
for i in range(1, 11):
if i == 6:
continue
else:
print(i, " ")

Output:

1 2 3 4 5 7 8 9 10

Pass Statements

The pass statement is a null operation; nothing happens when it executes. The pass statement
does nothing.

The difference between a comment and a pass statement in Python is that while the interpreter
ignores a comment entirely, pass is not ignored.

It can be used when a statement is required syntactically but the program requires no action. For
example:

This is commonly used for creating minimal classes:

Another place pass can be used is as a place-holder for a function or conditional body when you
are working on new code, allowing you to keep thinking at a more abstract level. The pass is
silently ignored:

Suppose we have a loop or a function that is not implemented yet, but we want to implement it in
the future. They cannot have an empty body. The interpreter would give an error. So, we use
the pass statement to construct a body that does nothing.

Example: Pass Statement

Chapter 4: Iteration
We can do the same thing in an empty function or class as well.

List

Python knows a number of compound data types, used to group together other values. The most
versatile is the list, which can be written as a list of comma-separated values (items) between
square brackets. Lists might contain items of different types, but usually the items all have the
same type.

numbers = [1, 2, 3, 4, 5]
food = ["cake", "burger", "fries"]

# print(numbers[index number])
print(numbers[0], food[1])

Output:
1 burger

Methods to control list and its objects

Methods Description
append() Appends object to list
count() Count how many times the object occur in list
extend() Appends the objects of other list
index() Return the index number of an object
insert() Insert object into list using index number
pop() Removes and returns the last object
remove() Removes object from a list
reverse() Reverse objects in place
sort() Sort objects

Changing value in a list

male = ['John', 'Mike']


print(male[0])
male[0] = "Frank"
print(male[0])

Output:
John
Mark

Adding object to a list

Chapter 4: Iteration
Using append()

numList = [1, 2, 3, 4, 5]
numList.append(99)
print(numList)

Output
[1, 2, 3, 4, 5, 99]

Using insert()

male = ['John','Mike']
male.insert(1,"Jake")
print(male)

Output
['John', 'Jake', 'Mike']

Removing object to a list

Using remove()

male = ['John','Mike','Jake']
male.remove("Jake")
print(male)

Output
['John', 'Mike']

Using pop()

male = ['John','Mike','Jake']
male.pop(1)
print(male)

Output
['John', 'Jake']

Arranging object in a list

Using sort()

numList = [20, 2, 33, 42, 25]


numList.sort()
print(numList)

numList.sort(reverse=True)

Output
[2, 20, 25, 33, 42

Chapter 4: Iteration
Using reverse()

numList = [20, 2, 33, 42, 25]


numList.reverse()
print(numList)

Output
[25, 42, 33, 2, 20]

Counting object

Using count()

numList = [25, 2, 33, 42, 25]


counter = numList.count(25)
print(counter)

Output
2

Checking object index

Using index()

numList = [11, 2, 33, 42, 25]


indexPosition = numList.index(42)
print(indexPosition)

Output
3

Combining lists

Using extend()

male = ['Bien','John']
female = ['Jayde','Ana']
male.extend(female)
print(male)
print(male[3])

Output
['Bien', 'John', 'Jayde', 'Ana']

Chapter 4: Iteration

You might also like