Loops
Executing a set of statements number of times based on some condition is called loop.
The loop is executed till the condition is true.
Type of loops
There are two types of loops used in Python
1. While loop
2. For loop
While Loop
While loop executes a set of statements as long as a condition is true.
while expression:
#execute your code
The while loop runs as long as the expression (condition) evaluates to True and execute
the statements. The condition is checked every time at the beginning of the loop. When
the expression evaluates to False, the loop stops without executing the statements
underneath.
The following example prints the digits 0 to 4 as we set the condition x < 5.
x = 0;
while (x < 5):
print(x)
x=x+1 # x += 1
Output:
0
1
2
3
4
while loop tests its condition before the body of the loop is executed. If the initial test
returns false, the body is not executed at all. For example, the following code never
prints out anything since before executing the condition evaluates to false.
x = 10;
while (x < 5):
print(x)
x += 1
Infinite Loop
The following while loop is an infinite loop, using True as the condition:
x = 10;
while (True):
print(x)
x += 1
The else Statement
The else statement is executed when the condition of while loop is no longer true. When
the condition specified with while loop becomes false and else statement is also used
then the block of statements under the else will be executed before finally coming out of
while loop.
In the following example, while loop calculates the sum of the integers from 0 to 9 and
after completing the loop, else statement executes.
x=0
s=0
while (x < 10):
s=s+x
x=x+1
else :
print('The sum of first 9 integers : ',s)
Output:
The sum of first 9 integers: 45
#Print a message once the condition is false.
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
The break Statement
With the break statement we can stop the loop even if the while condition is true. It
terminates the looping & transfers execution to the statement next to the loop.
#Exit the loop when i is 3.
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
The continue Statement
With the continue statement we can stop the current iteration, and continue with the
next. When continue statement is encountered within the loop, rest part of loop body is
skipped, and execution of the loop body is started again with the next iteration.
#Continue to the next iteration if i is 3.
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
For Loops
For loop is used when we know how many times a block of statement is to be executed.
For loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a
set, or a string).
for variable_name in sequence :
statement_1
statement_2
....
The range() Function
The range() function is used to loop through range of numbers. The range() function
returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and ends at a specified number.
The range() function returns a list of consecutive integers. The function has one, two or
three parameters where last two parameters are optional.
Syntax of range() function
range(a)
Generates a sequence of numbers from 0 to a -1, incrementing by 1.
for <variable> in range(<number>):
for a in range(5):
print(a)
Output:
0
1
2
3
4
range(5) is not the values of 0 to 5, but the values 0 to 4 as range () function by
default starts from 0.
range(a, b)
Generates a sequence of numbers from a to b – 1, incrementing by 1.
for "variable" in range("start_number", "end_number"):
for a in range(2,7):
print(a)
Output
2
3
4
5
6
range(a, b, c)
Generates a sequence of numbers from a to b - 1, incrementing by c.
for a in range(2,19,5):
print(a)
Output:
2
7
12
17
More examples:
range(1, 11) – 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
range(11) – 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
range(1,11,2) – 1, 3, 5, 7, 9
range(30,-4,-3) – 30, 27, 24, 21, 18, 15, 12, 9, 6, 3, 0, -3
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is
finished:
Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
Output:
0
1
2
3
4
5
Finally finished!
Nested Loops
A nested loop is a loop inside a loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
for a in range(1, 6):
for b in range(1, 3):
print ("%d * %d = %d" % (a, b, a*b))
Output:
1*1=1
1*2=2
2*1=2
2*2=4
3*1=3
3*2=6
4*1=4
4*2=8
5*1=5
5 * 2 = 10
Loop Control Statements
Break, Continue and Pass statements are used in the far loop similar to the while loop.
Assignment
Write the following program for your practical file
1. WAP to find the sum of a number.
2. WAP to print the table from 1 to 10 in the following format:
3. Write a program to determine whether a given natural number is a perfect number. A
natural number is said to be perfect number if it is the sum of its devisors. For
example, 6 is a perfect number because 6=1+2+3, but 15 is not a perfect number
because 15 ≠ 1+3+5.
4. WAP that return True or False depending on whether the given number is a
palindrome. A palindromic number is a number (such as 16461) that remains the
same when its digits are reversed.
5. WAP that prints Armstrong numbers in the range 1 to 1000. An Armstrong number is
a number whose sum of the cubes of the digits is equal to the number itself. For
example, 370=33 + 73+ 03.