0% found this document useful (0 votes)
3 views22 pages

Looping in Python

Chapter 12 of the tutorial focuses on looping in Python, covering various types of loops including while and for loops, as well as control statements like break and continue. It provides examples and explanations on how to use these constructs to perform repetitive tasks efficiently, such as printing natural numbers and calculating sums. Additionally, it introduces the range() function, which is commonly used with loops to generate sequences of numbers.

Uploaded by

hemil871
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views22 pages

Looping in Python

Chapter 12 of the tutorial focuses on looping in Python, covering various types of loops including while and for loops, as well as control statements like break and continue. It provides examples and explanations on how to use these constructs to perform repetitive tasks efficiently, such as printing natural numbers and calculating sums. Additionally, it introduces the range() function, which is commonly used with loops to generate sequences of numbers.

Uploaded by

hemil871
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit I: Computational Thinking and Programming - 1 Visit to website: learnpython4cbse.

com

Chapter- 12 Looping in Python

“There is a world of answers, outside the loop.”


You will learn the following topics in this tutorial
S. No. Topics
1 Introduction: Looping in python

2 while loop

3 while loop with else block:

4 The range ( ) function

5 for loop

6 Range( ) Function with For Loop

7 for loop with else block

8 Infinite loop

9 Nested Loop

10 Jump Control Statements:

11 1) Break statement

12 2) Continue statement

13 3) pass Statement:

`Page 1 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Objectives
After completing this lesson on Python Loops, you will be able to:

 Define loops and their types in python


 Explain Nested loop
 Describe the range function
 Explain the break and continue statements in a loop.

Introduction: Looping in python


 Often, we repeat a task, for example, we work hard to get paid at the
end of each month. This is done every month.
 This kind of repetition is also
called iteration. Repetition of a
set of statements in a program is
made possible using looping
constructs.
 Let us understand with the help
of small program
Program: Write a program to print the first five natural numbers.
Output:
#Print first five natural numbers print(1) 1
print(2) 2
print(3) 3
print(4) 4
print(5) 5
`Page 2 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

What should we do if we are asked to print the first 1000 natural


numbers? Writing 1000 print statements would not be an efficient
solution.
It would be tedious and not the best way to do the task.
Writing a program having a loop or repetition is a better solution.
The program logic is given below:
1. Take a variable, say count, and set its value to 1.
2. Print the value of count.
3. Increment the variable (count += 1).
4. Repeat steps 2 and 3 as long as count has a value less than or equal to
1000 (count <= 1000).
So, looping constructs provide the facility to execute a set of statements
in a program repetitively, based on a condition.
There are two looping constructs in Python - while and for.

`Page 3 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

1) while loop
 The while statement allows you to
repeatedly execute a block of
statements as long as a condition is
true
 It is entry-controlled loop i.e. it first
check the condition and if it is true
then allows entering in loop.
 while loop contains various loop
elements: initialization, test
condition, body of loop and update statement
Syntax:
while condition:
#body_of_while

Example 1: Program to print first 10 natural numbers using while loop.


num = 1 Initialization
# num <= 10 remains true
while num <= 10: Test Condition
print(num)
#incrementing the value of num Body of loop
num = num + 1 Update
condition
# loop will repeat itself as long as

`Page 4 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

while loop elements:


1. Initialization: it is used to give starting value in a loop variable from
where to start the loop. In above example num is initializing with 1
2. Test condition: it is the condition or last value up to which loop will be
executed. In above example num<=10 is test condition
3. Body of loop: it specifies the action/statement to repeat in the loop
4. Update statement: it is the increase or decrease in loop variable to
reach the test condition. In above example num=num+1 is update
condition.

Example 2: The program takes a number and generates all the divisors
of the number.
Coding:
n=int(input("Enter an integer:"))
print("The divisors of the number are:")
i=1
OUTPUT
while i<=n: Enter an integer: 10
if(n%i==0): The divisors of the number
are:
print(i)
1
i=i+1
2
5
10
`Page 5 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 3: The program takes in a number and checks if it is a prime


number using while loop.

Code:
n=int(input("Enter number: "))
count=0
i=2
while (i<=n//2):
if(n%i ==0):
count=count+1
i=i+1
if(count<=0):
print("Number is prime")
else:
print("Number isn't prime")

Program Explanation

1. User must enter the number to be checked and store it in a different


variable.
2. The count variable is first initialized to 0.
3. The while loop check to the half of the entered number.
4. The if statement then checks for the divisors of the number if the
remainder is equal to 0.
5. The count variable counts the number of divisors and if the count is
lesser or equal to 0, the number is a prime number.
6. If the count is greater than 0, the number isn’t prime.
7. The final result is printed.
`Page 6 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 4: The program takes in the number of terms and finds the sum
of series: 1 + 1/2 + 1/3 + ….. + 1/N.
CODE:

num=int(input("Enter the number of terms: "))

sum=0

i=1

while(i<=n):

sum=sum+(1/i)

i+=1

print("The sum of series is%10.2f" %sum1)

Program Explanation

1. User must enter the number of terms to find the sum of.
2. The sum variable is initialized to 0.
3. The while loop is used to find the sum of the series and the number is
incremented for each iteration.
4. The numbers are added to the sum variable and this continues till the
value of i reaches the number of terms.
5. Then the sum of the series is printed.

`Page 7 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

while loop with else block:


We can have an ‘else’ block associated with while loop. The ‘else’ block is
optional. It executes only after the loop finished execution.

Example 5: According to ideal Hindu wedding rituals, marriage is not


completed until bride and groom don't take 7 vows.

vow=1
while vow<=7:
print( "Bride and Groom take vow no:",vow )
vow+=1
else:
print( "Congratulation... Wedding Completed" )

Output:
Bride and Groom take vow no: 1
Bride and Groom take vow no: 2
Bride and Groom take vow no: 3
Bride and Groom take vow no: 4
Bride and Groom take vow no: 5
Bride and Groom take vow no: 6
Bride and Groom take vow no: 7
Congratulation... wedding completed
`Page 8 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

The range ( ) function:

Before we proceed to for loop let us understand range() function:

It generates a series of integers starting from a start value to a stop


value as specified by the user. We can use it with for loop and traverse
the whole range like a list.
The syntax of the range() function is as follows:
range (start, stop, step)
PARAMETER DESCRIPTION
Start (optional) Starting point of the sequence. It defaults to 0.

stop (required) Endpoint of the sequence. This item will not be included in the sequence.
step (optional) Step size of the sequence. It defaults to 1.

Function range can take one, two or three arguments.


 If we pass one argument to the function, in this case, range returns a
sequence in the range: 0 – ( end – 1 )
>>>list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
 If we pass two arguments, the first argument, called start, and the
second argument is end. In this case, range returns a sequence in the
range: ( start ) – ( end – 1 )
>>>list(range(2,10))
[2, 3, 4, 5, 6, 7, 8, 9]

`Page 9 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

 If we pass three arguments, the first two arguments are start and
end, respectively, and the third argument, called step, is the increment

value.
 If increment is positive, the last value in the sequence is the largest
multiple less than end value
>>>list(range(0,10,3))
[0, 3, 6, 9]
Here the range() function is called with a step argument of 3, so it will
return every third element from 1 to 20 (off course not including 20).
 The increment value of range also can be negative. In this case, it is a
decrement and the sequence produced progresses downwards from
start to end in multiples of the increment value. The last value in the
sequence is the smallest multiple greater than end value
>>> list(range(20,0,-2))
[20, 18, 16, 14, 12, 10, 8, 6, 4, 2]
 The range() function is commonly used with for loop to repeat an
action certain number of times.
For example, in the following listing, we use range() to execute the loop
body 5 times. OUTPUT:

for i in range(5): 0
1
print(i) 2
3
4
`Page 10 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

1) for loop
The for statement is used to iterate over a range of values or a sequence.

These values can be either


numeric, or they can be elements
of a data type like a string, list, or
tuple.
Working of for loop:
With every iteration of the for
loop, the control variable checks
whether each of the values in the
range have been traversed or not. When all the items in the range are
exhausted, the statements within loop are not executed; the control is
then transferred to the statement immediately following the for loop.
The syntax of the for loop:
for ctrl-variable in (sequence/ items in range):
statements inside body of the loop

The “ctrl-variable” represents the iterating variable. It gets assigned


with the successive values from the input sequence.
The “sequence” may refer to any of the following Python objects such
as a list, a tuple or a string.

`Page 11 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 6: – Print Characters of a String OUTPUT:

str="PYTHON" Character: P
Character: Y
for ctrl in str: Character: T
Character: H
print("Character: ", ctrl)
Character: O
The above code is traversing the characters Character: N
in the input string named as the str.

Example 7: Find the Average of N Numbers


lst = [2, 4, 6, 8, 10, 12]

sum = 0

for ctrl in lst:


OUTPUT:
sum += ctrl
Sum = 42
avg = sum/(len(lst)) Avg = 7.0
print("Sum =", sum)

print("Avg =", avg)

Range( ) Function with For Loop:


NOTE: The change in the third argument to range for loops that
decrement the control variable.
The following examples show techniques for varying the control variable
(loop counter) in a for structure.
`Page 12 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

 Vary the control variable from 1 to 50 in increments of 1.


for ctr in range( 1, 51 ):
print(ctr)
 Vary the control variable from 50 to 1 in increments of –1 (decrements
of 1).
for ctr in range( 50, 0, –1 ):
print(ctr)
 Vary the control variable from 7 to 77 in steps of 7.
for ctr in range( 7, 78, 7 ):
print(ctr)
 Vary the control variable from 20 to 2 in steps of -2.
for ctr in range( 20, 1, -2 ):
print(ctr)
 Vary the control variable over the following sequence of values:
2, 5, 8, 11, 14, 17, 20.
for ctr in range( 2, 21, 3 ):
print(ctr)

 Vary the control variable over the following sequence of values:


99, 88, 77, 66, 55, 44, 33, 22, 11, 0.
for ctr in range( 99, -1, -11 ):
print(ctr)

`Page 13 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 8: Program to Find the Sum of Digits in a Number


Coding:
n = input("Enter a number: ")
tot = 0
l = len(n)
OUTPUT:
num = int(n)
for i in range(l): Enter a number: 1234
The total sum of digits is: 10
if(num>0):
dig = num%10
tot = tot + dig
num = num//10
print("The total sum of digits is: ",tot)

Example 9: Program to print the Fibonacci series first N terms.

0,1,1,2,3,5,8,13…….
Coding:
N = int(input("Enter the number of terms: "))
f=0
s=1
print("Fibonacci series: ")
print(f, end=' ') # Print first term of series
print(s, end=' ') # Print second term of series
for i in range(1, N-1):
OUTPUT:
t = f + s
print(t, end=' ') Enter a number: 1234
f, s = s, t The total sum of digits is: 10

`Page 14 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 10: Program to check if a Number is a Palindrome


Code:
n = input("Enter a number: ")
tot = 0
l = len(n)
num = int(n)
temp = num
rev = 0
for i in range(l):
if(num>0):
dig = num % 10
rev = rev * 10 + dig
num = num // 10

if ( rev == temp):
print("Number is Palindrome")
else:
print("Number is Not a Palindrome")

OUTPUT:
Enter a number: 122
Number is Not a Palindrome

Enter a number: 121


Number is Palindrome

`Page 15 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

else Clause with Python for Loop


 The code under the else clause executes after the completion of
the “for” loop.
 However, if the loop stops due to a “break” call, then it’ll skip
the “else” clause.
Syntax: for-else
for item in seq:
statement 1

statement 2

if <cond>:
break
else:
statements

Example 11:

for a in range(3):
print(a)
if a==4: # change value to force break or not
break OUTPUT:
else: #no break 0
1
print('for completed OK')
2
print('statement after for loop') for completed OK
statement after for loop
 In the above code, If does not encounter the break command in
the for loop, so the else part will be called as shown in output

`Page 16 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 12:

for a in range(3):
print(a)
if a==4: # change value to force break or not
break OUTPUT:
else: #no break 0
1
print('for completed OK')
2
print('statement after for loop') statement after for loop

 In the above code, If encounter the break command in the for loop, so
the else part will not be called as shown in output

Infinite loop
An infinite loop that never ends; it never breaks out of the loop.

So, whatever is in the loop gets executed forever, unless the program is
terminated.

Example 13:

# press Ctrl + c to exit from the loop

while True:

name = input("Enter Your name: ")

print("Your Name is: " , name)

The above given code never end unless the program terminated.
`Page 17 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Nested Loop:
 A loop may contain another loop inside it.
 A loop inside another loop is called a nested loop.
 Following section shows few examples to illustrate the concept.

Syntax
for itr_var in sequence:
for ite_var in sequence:
statements(s)
statements(s)

The syntax for a nested while loop statement in Python programming


language is as follows −
while expression:
while expression:
statement(s)
statement(s)

A final note on loop nesting is that you can put any type of loop inside of
any other type of loop. For example a for loop can be inside a while loop
or vice versa.

`Page 18 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example 14: The following program uses a nested for loop to find the
prime numbers from 2 to 20 −
for a in range(2,21):
OUTPUT:
k = 0
2 is prime
for i in range(2,a//2+1): 3 is prime
5 is prime
if(a%i = = 0): 7 is prime
11 is prime
k = k+1 13 is prime
17 is prime
if(k <= 0):
19 is prime
print(a,"is prime") Good bye!
print ("Good bye!")

Example 15: The following program uses a nested while loop to find the
prime numbers from 2 to 20 −
i = 2
while(i < 20): OUTPUT:
j = 2 2 is prime
3 is prime
while(j <= (i/j)):
5 is prime
if not(i%j): # factor found 7 is prime
break #break out of while loop 11 is prime
13 is prime
j = j + 1 17 is prime
if (j > i/j) : #no factor found 19 is prime
Good bye!
print (i, " is prime")
i = i + 1
print ("Good bye!")
`Page 19 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Program Output
Example 16 1
2 2
for i in range(1,6):
3 3 3
for j in range(0,i):
print(i, end=" ") 4 4 4 4
print('') 5 5 5 5 5

Example 17 1 1 1 1 1
2 2 2 2
for i in range(1,6):
for j in range(5,i-1,-1): 3 3 3
print(i, end=" ") 4 4
print('')
5

Jump Control Statements:


Jump statements are used to transfer the program's control from one location to
another. Means these are used to alter the flow of a loop like-to skip a part of a loop
or terminate a loop

There are three types of jump statements used in python.

1. break

2. continue

3. pass

`Page 20 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

1) Break statement 2) Continue statement


The break statement is used to exits the The continue statement is used to skip
loop immediately, and unconditionally the current block and move ahead to
ends the loop's operation. the next iteration, without executing
the statements inside the loop.

`Page 21 of 22
Unit I: Computational Thinking and Programming - 1 Visit to website: [Link]

Chapter- 12 Looping in Python

Example: Example:

In this program, we iterate through This program is same as the break


the "python" sequence. We check if the example except the break statement has
letter is ‘o’, upon which we break from been replaced with continue.
the loop. Hence, we see in our output
We continue with the loop, if the string
that all the letters up till ‘o’ gets printed.
is ‘o’, not executing the rest of the block.
After that, the loop terminates.
Hence, we see in our output that all the
letters except ‘o’ gets printed.

3) pass Statement:
 pass in Python basically does nothing, but unlike a comment it is not ignored
by interpreter.
 It can be used when a statement is required syntactically but the program
requires no action.
Can be use in loop and conditional statements:

if (something == true): # used in conditional


pass # Statement

while (some condition is true): # user is not sure about


pass # the body of the loop
`Page 22 of 22

You might also like