Professional Documents
Culture Documents
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.
Types:
while loop
for loop
o In
o Range
Chapter 4: Iteration
Lesson 4.1 While Loop Iteration
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.
while test_expression:
Body of while
If the condition is initially false, the loop body will not be executed
at all.
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).
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.
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
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:
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.
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
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):
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.
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:
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.
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 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
Output:
John
Mark
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']
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']
Using sort()
numList.sort(reverse=True)
Output
[2, 20, 25, 33, 42
Chapter 4: Iteration
Using reverse()
Output
[25, 42, 33, 2, 20]
Counting object
Using count()
Output
2
Using index()
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