Laboratory No. 4
Laboratory No. 4
Laboratory No. 4
COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
City of Malolos Bulacan
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:
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:
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print "No items left."
Output:
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:
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?".
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