0% found this document useful (0 votes)
112 views

B. The For Loop Statement

The document discusses the for loop statement in Python. It provides examples of using a for loop to iterate through a list and print each element, calculate the sum of numbers in a list, and count the number of times a letter appears in a string. It also discusses using the range() function to generate sequences of numbers to iterate over in a for loop. The break statement is shown to exit the loop if a certain condition is met.

Uploaded by

W. Loya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
112 views

B. The For Loop Statement

The document discusses the for loop statement in Python. It provides examples of using a for loop to iterate through a list and print each element, calculate the sum of numbers in a list, and count the number of times a letter appears in a string. It also discusses using the range() function to generate sequences of numbers to iterate over in a for loop. The break statement is shown to exit the loop if a certain condition is met.

Uploaded by

W. Loya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

B.

The for loop statement


The general form of for loop is :
for var_name in sequence/functions :
statement-1
statement-2 body of the loop
statement-3
statement-x
Example :
Printing each word in a list of strings using for loop.

words = ['this', 'is', 'an', 'example'] # A sequence (list)


for word in words: for c in words:
print word, print c,
Dr. M. Shubhakanta Singh
for loop – Example 1
Example 1: Write a Python program to find the sum of all the
numbers stored in a list(a collection of elements).
Solution:
# Sum of all numbers stored in a list
numbers = [5, 10, 15, 20, 25, 30, 35, 40]
SUM = 0

for n in numbers:
SUM = SUM + n
print("The sum of the numbers=", SUM)

Output of this program:


The sum of the numbers= 180
Dr. M. Shubhakanta Singh
for loop – Example 2
Example 1: Write a Python program to find the sum of all
the numbers stored in a list(a collection of elements).
Solution:
# Program to print squares of all numbers present in a list
numbers = [1, 2, 4, 6, 7, 10] Output of this
sqr = 0 program:
print("\nThe square of the numbers are:") The square of the
for no in numbers: numbers are:
sqr = no * no 1 1
print('{0:2d} {1:3d}'.format(no, sqr)) 2 4
4 16
6 36
7 49
10 100
Dr. M. Shubhakanta Singh
for loop – Example 3
Example
Example:: To count the number Example
Exercise : Encapsulate this code in a
of times the letter a appears in function named count
a string: def count(string, letter):
word = 'banana' count = 0
count = 0 for character in string:
if character == letter:
for letter in word: count = count + 1
if letter == 'a': return count
count = count + 1
str1='banana'
print (count) letter ='a'
counter = count(str1, letter)
print ('No of the character',
'"',letter,'"',' present =',
counter)
Output of the Program:
No of the character " a "Singhpresent = 3
Dr. M. Shubhakanta
for loop – Example 4 (advanced)

o print(" ".join("Hello" for _ in range(10)))


o print(*("Hello" for _ in range(10)))
o print(*["Hello" for _ in range(10)])
Note: The above line can be written as follows:
o print(*["Hello" for x in range(10)])

Output of this program:


Hello Hello Hello Hello Hello Hello Hello
Hello Hello Hello

Dr. M. Shubhakanta Singh


xrange() and range() function
In Python 2.x we can used both xrange() and range() functions. However in Python 3.x
we cannot use xrange() function. xrange() takes less memory than range() function.
range() in Python 3.x is just a renamed version of the xrange() function in Python 2.x.

# Python code to demonstrate range() vs xrange()


# on basis of return type
import sys
# initializing a with range() # initializing a with range()
abc = range(1,10000) a = range(1,10000)
# initializing a with xrange() # initializing a with xrange()
xyz = xrange(1,10000) x = xrange(1,10000)
# testing the type of abc # testing the size of a
print ("The return type of range() is : ") # range() takes more memory
print (type(a)) print ("The size allotted using range() is : ")
print (sys.getsizeof(a))
# testing the type of xyz
print ("The return type of xrange() is : ")
print (type(x))

Dr. M. Shubhakanta Singh


The range() function
To iterate over a sequence of numbers, Python provides the
built-in function range() which can generates lists containing
arithmetic progression.
range(argument1)
range(argument1, argument2)
range(argument1, argument2, argument3)
>>> range(10) # range(End Value)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 15) # range(Starting value, End Value)
[5, 6, 7, 8, 9, 10, 11, 12, 13, 14] # starting value may be negative also
>>> range(0, 10, 3) # range(Starting value, End value, step size)
[0, 3, 6, 9]
Dr. M. Shubhakanta Singh
The range() function- examples
# range() function with one argument
for i in range(10):
# print (i) This will print in different lines
print(i) option:
0

print (i, end=' ')


1
2

#range() function with two arguments


3
4
for i in range(2,10): 5
6
print (i, end=' ') 7

#range() function with three arguments


8
9

for i in range(1,10,2):
print (i, end=' ')
Output of the above Programs:
0 1 2 3 4 5 6 7 8 9
23456789
13579
Dr. M. Shubhakanta Singh
The range() function- examples
# incremented by -2
for i in range(20,3,-2):
print (i, end=' ')

#Sum of the first natural numbers


SUM = 0
for i in range(1,11):
SUM = SUM + i
print ("\nSum of first 10 natural numbers:", SUM)
Output of the
# Concatenate the range function. programs:
from itertools import chain 20 18 16 14 12 10 8 6 4
print("\n Concatenating the result")
result = chain(range(7), range(10, 20, 2)) Sum of first 10 natural

for i in result:
numbers: 55

print (i, end=' ') Concatenating the result


0 1 2 3 4 5 6 10 12 14 16 18
Dr. M. Shubhakanta Singh
Important rules for using the range()
 range() function works only with the integers i.e. whole
numbers.
 All arguments must be integers. User can’t pass a string
or float number or any other type in a start, end and
step arguments of a range() function.
 All three arguments can be either positive or negative.
 The step value must not be zero. If a step is zero,
Python raises a ValueError exception.
 range() is a type in Python.
Example: print (type(range(4)))
Output: <class 'range'>
• print (range(10)[3]) # 3
• print (range(5,20)[5])# 10
Dr. M. Shubhakanta Singh
The break Statement

while (condition-1) : for … in … :


……………… ………………
……………… ………………
if (condition-2) : if (condition-1) :
break break
……………… ………………
……………… ………………

statement-x statement-x

Dr. M. Shubhakanta Singh


The break Statement - example
from math import sqrt
no = int(input("Enter a number :"))
while True :
sqr_rt = sqrt(no)
print ("The square root of the number " ,no, " is ",sqr_rt)
no = int(input("Enter a number :"))
if no < 0 :
print ("Negative numbers can't have square roots....!")
break
Output of the programs:
Enter a number :12
The square root of the number 12 is 3.4641016151377544

Enter a number :-8


Negative numbers can't have square roots....!
Dr. M. Shubhakanta Singh

You might also like