Laboratory No. 4

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

BULACAN STATE UNIVERSITY

COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
City of Malolos Bulacan

COMPUTER FUNDAMENTALS AND PROGRAMMING


LABORATORY NO. 4
LOOPS
NAME: __________________________________________________ SCORE: __________________
C/Y/S: ___________________________________________________ DATE: __________________

I. Objective: To develop simple programs using loop statements.


II. Software: Python 2.7.14 or newer versions
III. Discussion/Procedures
What is for loop in Python?
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects.
Iterating over a sequence is called traversal.
Syntax of for Loop

for val in sequence:


Body of for

val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues
until we reach the last item in the sequence. The body of for loop is separated from the rest of the code
using indentation.
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]
sum = 0
for val in numbers:
sum = sum+val
print('%d' %(sum))
print "The sum is", sum
Output:

The range() function


We can generate a sequence of numbers using range() function. range(10) will generate numbers
from 0 to 9 (10 numbers). We can also define the start, stop and step size as range(start,stop,step size). step
size defaults to 1 if not provided. This function does not store all the values in memory, it would be
inefficient. So it remembers the start, stop, step size and generates the next number on the go. To force this
function to output all the items, we can use the function list().

print(list(range(2, 20, 3)))


print range(10)
print list(range(10))
print list(range(2, 8))
1
print list(range(2, 20, 3))

Output:

We can use the range() function in for loops to iterate through a sequence of numbers. It can be
combined with the len() function to iterate though a sequence using indexing. Here is an example.
genre = ['pop', 'rock', 'jazz','classical','rap', 'country','ballad', 'R&B']
for i in range(len(genre)):
print "I like", genre[i]
Output:

for loop with else


A for loop can have an optional else block as well. The else part is executed if the items in the
sequence used in for loop exhausts. break statement can be used to stop a for loop. In such case, the else
part is ignored. Hence, a for loop's else part runs if no break occurs.

digits = [0, 1, 5]

for i in digits:
print(i)
else:
print "No items left."
Output:

Syntax of while Loop in Python

while test_expression:
Body of while

In 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

2
through indentation. 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.

n = int(input("Enter n: "))
sum = 0
i=1

while i <= n:
sum = sum + i
i = i+1
print('%d' %(sum))
print "The sum is", sum
Output:

WHEN DO I USE FOR LOOPS?


for loops are traditionally used when you have a block of code which you want to repeat a fixed
number of times. 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 x in range(0, 3):


print "We're on time %d" % (x)
Output:

While loop from 1 to infinity, therefore running forever.


x=1
while True:
print "To infinity and beyond! We're getting close, on %d now!" % (x)
x += 1
Describe the output from the above code:

These loop constructs serve different purposes. The for loop runs for a fixed amount - in this case,
3, while the while loop runs until the loop condition changes; in this example, the condition is the boolean
3
True which will never change, so it could theoretically run forever. You could use a for loop with a huge
number in order to gain the same effect as a while loop, but what's the point of doing that when you have a
construct that already exists? As the old saying goes, "why try to reinvent the wheel?".

HOW DO THEY WORK?


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.
for x in xrange(1, 3):
for y in xrange(1, 11):
print '%d * %d = %d' % (x, y, x*y)
Output:

EARLY EXITS
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 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 x in xrange(0, 100):
print "%d" %(x)
if x == 19:
break

THINGS TO REMEMBER
range vs xrange
The ''range'' 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 which returns a sequence, which meets the requirement of providing

4
a sequence for the for statement to iterate over. In Python 2.x, range generates the entire sequence when
called, while xrange is a generator - it produces values on demand, not all up front. You will often see
xrange is used much more frequently than range. This is for one reason only - resource usage. For large
sequences, the difference in memory usage can be considerable. xrange uses less memory, and should the
for loop exit early, there's no need to waste time creating the unused numbers. This effect is tiny in smaller
lists, but increases rapidly in larger lists as you can see in the examples below. For Python 3.x, range was
changed, you can think of it as being equivalent to the Python 2.x xrange, which no longer defined in Python
3.x.
Examples
For..Else
for x in xrange(3):
print x
else:
print 'Final x = %d' % (x)
Output:

Strings as an iterable
string = "Hello World"
for x in string:
print x
Output:

Lists as an iterable
collection = ['hey', 'BSCpE', '5th year']
for x in collection:
print x
Output:

5
IV. PROGRAMMING CHALLENGE
1. Based on the given sample dialogue, write a python program based on the given output.
SAMPLE DIALOGUE 1:
Enter a limit: 4 SAMPLE DIALOGUE 2:
Even numbers from 0 to 4 Enter a limit: 9
0 Even numbers from 0 to 9
2
0
4
2
Odd numbers from 0 to 4 4
1 6
3 8

Odd numbers from 0 to 9


1
3
5
7
9
2. Based on the given LIST
l=[0,5,10,15,20,25,1,2,4,12,13,90,8,23,67,89,45,34,145,82,5,76,67,43,32,45,12,56,78,87,810]
write a python program based on the given output.
Even numbers are:
0
10
20
2
4
12
90
8
34
82
76
32
12
56
78
810
Odd numbers are:
5
15
25
1
13
23
67
89
45
145
5
67
43
6
45
87
>>>.
WRITE YOUR CODE AT THE BACK OF THIS PAGE.

You might also like