Thursday, November 7, 2019

LOOPS IN PYTHON.

ITERATION/LOOPING.

Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Repeated execution of a set of statements is called iteration. Because iteration is so common, Python provides several language features to make it easier.


Python programming language provides the following types of loops to handle looping requirements. Python provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition checking the time.
While Loop:
  • In python, while loop is used to execute a block of statements repeatedly until a given a condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed.
  • Syntax :
while expression:

       statement(x)


All the statements indented by the same number of character spaces

 after a programming construct are considered to be part of a single

 block of code. Python uses indentation as its method of grouping

statements.

Example:

# Python program to illustrate 

# while loop 
count = 0
while (count < 3):  
count = count + 1
print("Hello ") 

output:
hello
hello
hello

Using else statement with while loops: As discussed above, while

 loop executes the block until a condition is satisfied. When the 

condition becomes false, the statement immediately after the loop

 is executed.

The else clause is only executed when your while condition 

becomes false. If you break out of the loop, or if an exception is 

raised, it won’t be executed.

If else like this:


if condition: 


# execute these statements 

else: 

# execute these statements 

and while loop like this is similar


while condition: 
# execute these statements 
else: 
# execute these statements 


#Python program to illustrate 
# combining else with while 
count = 0
while (count < 3):  
count = count + 1
print("Hello ") 
else: 
print("In Else Block") 

output:
Hello
Hello
Hello
In Else Block

Single statement while block: Just like the if block, if the while 

block consists of a single statement we can declare the entire 

loop in a single line as shown below:



# Python program to illustrate 

# Single statement while the block 
count = 0
while (count == 0): print("Hello Geek") 


Note: It is suggested not to use this type of loops as it is a never-ending infinite loop where the condition is always true and you have to forcefully terminate the compiler.
See this for an example where while loop is used for iterators. As mentioned in the article, it is not recommended to use a while loop for iterators in python.
for loop: For loops are used for sequential traversal. For example: traversing a list or string or array etc. In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is a “for in” loop which is similar to for each loop in other languages. Let us learn how to use for in loop for sequential traversals.
Syntax:
for iterator_variable in sequence:
           statement(s)

It can be used to iterate over iterators and a range.

# Python program to illustrate 

# Iterating over a list 

print("List Iteration") 

l = ["pari", "for","paritosh"]

for i in l: 

print(i) 

# Iterating over a tuple (immutable) 

print("\nTuple Iteration") 

t = ("paritosh","for","paritosh")

for i in t: 

print(i) 

# Iterating over a String 

print("\nString Iteration")  

s = "paritosh"

for i in s : 

print(i) 

# Iterating over dictionary 

print("\nDictionary Iteration") 

d = dict() 

d['xyz'] = 123

d['abc'] = 345

for i in d : 

print("%s %d" %(i, d[i])) 


output:

List iteration
pari
for
Paritosh

Tuple iteration
Paritosh
for
Paritosh


string iteration
p
a
r
i
t
o
s
h

dictionary iteration
XYZ  123
ABC  345


Iterating by an index of sequences: We can also use the index of 

elements in the sequence to iterate. The key idea is to first calculate

 the length of the list and in iterate over the sequence within the 

range of this length.

See the below example:

# Python program to illustrate 

# Iterating by index 

list = ["paritosh","for","paritosh"]

for index in range(len(list)): 

print list[index] 

output:

Paritosh

for 

Paritosh


Using else statement with for loops: We can also combine else 

statement with for loop like in while loop. But as there is no 

condition in for loop based on which the execution will terminate 

so the else block will be executed immediately after for block

 finishes execution.

Below example explains how to do this:

# Python program to illustrate 
# combining else with for 

list = ["paritosh","for","paritosh"]
for index in range(len(list)): 
print list[index] 
else: 
print "Inside Else Block"
output:

paritosh

for

paritosh

Inside Else Block



We can use for in loop for user-defined iterators. See this for example.
Nested Loops: Python programming language allows to use one

 loop inside another loop. The following section shows a few

examples to illustrate the concept.


Syntax:

for iterator_var in sequence: 
for iterator_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 we 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.


# Python program to illustrate 

# nested for loops in Python 

from __future__ import print_function 

for i in range(1, 5): 

for j in range(i): 

print(i, end=' ') 

print() 

output:

1
2  2
3  3  3
4  4  4  4


Loop Control Statements: 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. Python supports the following control statements.


Continue Statement: It returns the control to the beginning of the 

loop.


# Prints all letters except 'e' and 's' 


for letter in 'paritosh singh':

if letter == 'e' or letter == 's': 

continue

print 'Current Letter :', letter 

var = 10

Break Statement: It brings control out of the loop.


for letter in 'Paritosh':

# break the loop as soon it sees 'e' 

# or 's' 

if letter == 'e' or letter == 's': 

break

print 'Current Letter :', letter 


Pass Statement: We use pass statement to write empty loops. Pass 

is also used for empty control statements, functions and classes.



# An empty loop 
for letter in 'paritosh':
pass
print 'Last Letter :', letter 




Exercise: How to print a list in reverse order (from last to the first item) using while and for-in loops.
PURPOSE OF LOOPING:
 loop in python is used to execute a block of statements or code several times until the given condition becomes false. We use for loop when we know the number of times to iterate. Here var will take the value from the sequence and execute it until all the values in the sequence are done.

1 comment:

if you have any doubt please let me know.

LOOPS IN PYTHON.

ITERATION/LOOPING. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. Repe...

recent one