LOOPING IN PYTHON
Looping is also called as
repetition structure. A
repetition structure allows
the programmer that an
action is to be repeated until
given condition is true.
Python allows a procedure or
block of statements to be
repeated as many times as
long as the processor could
support.
Repeats a statement or Executes a sequence of We can use one or more
group of statements statements multiple loops inside another
when a given condition times and abbreviates while, for or while loop.
is true. It tests the the code that manages
condition before the loop variable
executing the loop body.
Common structure for all types of loop
• There is a control variable, called the Loop Counter
• The control variable must be initialized.
• The increment/decrement of the control variable, which is
modified each time the iteration of the loop occurs.
While loop
• The while loop in Python is used to iterate over a block of code as long as
the test expression (condition) is true.
• We generally use this loop when we don't know beforehand, the number of
times to iterate.
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 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.
In this program, the test
expression will be True as long
as our counter variable i is less
than or equal to n (10 in our
program).
We need to increase the value of
counter variable in the body of
the loop. This is very important
(and mostly forgotten). Failing to
do so will result in an infinite
loop (never ending loop).
Finally the result is displayed.
Flowchart and Python program to print the numbers from 1 to 10
FLOWCHART PYTHON PROGRAM
Start #to print the numbers from 1 to 10
#using while loop
count=1 count=1
while (count<11):
print ("The count is: ", count)
false
Is count=count+1
count<11
? print ("Thank you")
true
Print count
Count=count+1 output
Stop
Flowchart and Python program to find the sum of 10 natural numbers.
FLOWCHART PYTHON PROGRAM
Start #to find the sum of 10 natural numbers
ctr=1
Sum=0, ctr=0 sumn=0
while (ctr<=10):
sumn=sumn+ctr
no
Is ctr=ctr+1
Print sum
ctr<=10? print ("The sum of numbers is :", sumn)
yes
1+2+3+4+5+6+7+8+9+10=55
sum=sum+ctr
ctr=ctr+1 output
Stop
Flowchart and Python program to find the factorial of an input number
FLOWCHART PYTHON PROGRAM
Start
#To find the factorial of a an input number
facto=ctr=1
Read n
n=int(input("Enter any number"))
Facto=1, ctr=1 while (ctr<=n):
facto=facto*ctr
Fact=fact*ctr ctr+=1
print("Factorial of %d is %d"%(n,facto))
yes
no
If
ctr<=n?
Ctr=ctr+1 Factorial of 8
Print 1*2*3*4*5*6*7*8=40320
facto
output
Stop
To find the Highest Common Factor
Numbers are 420 and 396
Flowchart and Python program to accept two numbers and print their HCF and
LCM
x= int(input("Enter first integer"))
y= int(input("Enter second integer"))
a=x
b=y
while(b != 0 ):
t=b
b=a%b
a=t
hcf = a
lcm = (x*y)/hcf
print("HCF of %d and %d is %d\n" %(x,y,hcf))
print("LCM of %d and %d is %d\n" %(x,y,lcm))
The Infinite Loop
• A loop becomes infinite loop if a condition never becomes false and results in a
loop that never ends. Such a loop is called infinite loop
For e.g. in the given flowchart where the
var is assigned to 1 and does not change
its value and continuously execute the
statements. Because the condition always
produce true result.
x=1
while x == 1:
print('hello')
The else statement used to while Loop
Python supports to have an else statement associated with while
loop. If the else statement is used with a while loop. If the else
statement is used with the while loop, the else statement is
executed when the condition becomes false.
output
#program to demonstrate else
statement #with while loop
ctr=5
while ctr<10:
print("%d is less than 10 "%ctr)
ctr=ctr+1
else:
print("%d is not less than 10 "%ctr)
for loop
• The for loop in Python has the ability to iterate of any sequence, such as a
list or a string.
For iterating_var in
sequence
Syntax statement(s)
If no more item
for iterating_var in sequence: More items in sequence
statement(s) in
else: <sequence> no
statement(s)
yes
var=next item
Execute body statement(s)
or
<body>
examples
#Program to demonstrate for loop
for name in "Ashok":
print ("Current Characters is :", name)
#to print the list values using for loop
num=[0,1,2,3,4,5,5,6,7]
for i in num:
print (i, end=" ")
Using range () function
We can generate a sequence of numbers using range() function. This function
does not store all the values in the memory, it would be insufficient . It just
remembers the start, stop, step size and generates the next number on the go. It
is more often used in for loops. The arguments must be plain integers. The
general format of range() function is:
range([start,]stop[,step])
Here
• Start and step are optional
• Start is the starting number of range . If the start argument is omitted, it
defaults to 0
• stop is the last number of range where the range will end where the range will
end. This is the exact end position is : stop -1.
• Step is the increment
The range() function generates lists containing arithmetic progressions
#program to print the table of 2
for num in range(2,22, 2):
print (num)
#program to print the number
in reverse order from 20 to 0
for num in range(20,0, -2):
print (num)
#program to print the prime number between 2 and 20
print("The prime numbers are ", end=" ")
for num in range(2,20): #to iterate between 2 to 20
for i in range(2,num): #to iterate on the factors of numbers
if num%i==0: # to determine the first factor
break # to move to the next number, the #first for
else: #part of the i for loop
#loop fell through without finding a factor
print(num, end=" ")
output
A positive integer greater than 1 which has no other factors except 1 and the number itself
is called a prime number.
2, 3, 5, 7 etc. are prime numbers as they do not have any other factors. But 6 is not prime
(it is composite) since, 2 x 3 = 6.
To check whether a number is palindrome or not
string=input("Enter string:")
if(string==string[::-1]):
print("The string is a palindrome")
else:
print("The string isn't a palindrome")
#to find the factorial of a number output
#demonstration of nested loop to find
the factorial of all the numbers
#between 1 and 6
#outer loop
for i in range(1,7):
fact=1
#inner loop
for factor in range(2, i+1):
fact=fact*factor
print("%i!is%10.2f"%(i,fact))
The factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 = 720. Factorial is not
defined for negative numbers and the factorial of zero is one, 0! = 1.
Patterns in Python
for i in range(3): for i in range(3): for i in range(3):
for j in range(3): for j in range(3): for j in range(3):
print(“8",end=“ ") print(“8",end=“ ") print(“8",end=“ ")
print() print() print()
Loop control statements change execution from its normal sequence. When
execution leaves a scope, all automatic objects that were created in that scope
are destroyed.
Break
statement
Loop control
statements
Pass Continue
Statement Statement
Break Statement
break Statement in Python is used to terminate the loop.
for letter in 'happylife': for i in range(10):
# break the loop as soon it sees ‘y' print(i)
# or ‘l' if(i == 7):
if letter == 'y' or letter == 'l':
print('break')
break
break
print (('Current Letter :'), letter)
# printing table from 2 to 5, each
table upto 5 iterations only
for i in range(2,6):
print('Table of ',i)
for j in range(1,11):
print(i*j)
if (j == 5):
break
Continue Statement
Continue Statement in Python is used to skip all the remaining
statements in the loop and move controls back to the top of the loop.
# Prints all letters except 'e' and 's'
for letter in "i love informatics practices":
if letter == 'e' or letter == 's':
continue
print ('Current Letter :', letter)
To skip the printing 3 and 8 in the loop
# Prints all letters except '3' and '8'
for num in range(0,20):
if num == 3 or num == 8:
continue
print ('The number is :', num)
pass statement
• We use pass statement to write empty loops. Pass is also used for empty
control statement, function and classes.
# An empty loop
for letter in 'i love informatics practices':
pass
print ('Last Letter :', letter)
for i in 'hello':
if(i == 'e'):
print('pass executed')
pass
print(i)
print('----')
for i in 'hello':
if(i == 'e'):
print('continue executed')
continue
print(i)
pass statement simply does nothing. We use pass statement
when you create a method that you don't want to implement,
yet.
Where continue statement skip all the remaining statements in
the loop and move controls back to the top of the loop.