For & While Loops

There are two types of loops in Python, for and while. A loop statement allows us to execute a statement or group of statements multiple times.

Python programming language provides following types of loops to handle looping requirements.

Loop Type Description
While Loop Repeats a statement or group of statements while a given condition is TRUE. It tests the condition before executing the loop body.
For Loop Executes a sequence of statements multiple times and abbreviates the code that manages the loop variable.
Nested loop You can nest any loop inside any loop to multiply the multiply repetitive instance.

Python while Loop Statements

A while loop statement in Python programming language repeatedly executes a target statement as long as a given condition is true. 

Syntax

The syntax of a while loop in Python programming language is ?

while expression:
   statement(s)

Here, statement(s) may be a single statement or a block of statements. The conditionmay be any expression, and true is any non-zero value. The loop iterates while the condition is true.

Example

#!/usr/bin/python

count = 0
while (count < 9):
   print 'The count is:', count
   count = count + 1

print "Last Line!"

Result : 

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Last Line!

The Infinite Loop

A loop becomes infinite loop if a condition never becomes FALSE. You must be cautious when using while loops because of the possibility that this condition never resolves to a FALSE value. This results in a loop that never ends. Such a loop is called an infinite loop.

An infinite loop might be useful in client/server programming where the server needs to run continuously so that client programs can communicate with it as and when required.

#!/usr/bin/python

var = 1
while var == 1 :
   num = raw_input("Enter a number  :")
   print "You entered: ", num

print "Last Line!"

save above code by name "infinite.py" and run the above program by opening terminal or command prompt and executing below code :-

python infinite.py

and let us know on "disqus" or "facebook" , how did you experience it. To close infinite loop, you can press "ctrl   C" command .

Using else Statement with Loops

Python supports to have an else statement associated with a loop statement.

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.

  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

#!/usr/bin/python

count = 0
while count < 10:
   print count, " is  less than 10"
   count = count + 1
else:
   print count, " is not less than 10"

Result : 

0 is less than 10
1 is less than 10
2 is less than 10
3 is less than 10
4 is less than 10
5 is less than 10
6 is less than 10
7 is less than 10
8 is less than 10
9 is less than 10
10 is not less than 10

One line While Statement

Below is another example of "infinite loop". To stop, please press "ctrl C".

#!/usr/bin/python

ctf = 1

while (ctf): print 'Given ctf is running in loop'

print "Last Line!"

Python for Loop Statements

It has the ability to iterate over the items of any sequence, such as a list or a string.

Syntax

for iterating_var in sequence:
   statements(s)

Example

#!/usr/bin/python

for letter in 'Python': 
   print 'Current Letter :', letter

mylist = ['john', 'doe',  'coder']

for elist in mylist:  
   print 'Current list :', elist

print "Last Line!"

Result :

Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : john
Current fruit : doe
Current fruit : coder
Last Line!

Iterating by Sequence Index

An alternative way of iterating through each item is by index offset into the sequence itself.

#!/usr/bin/python

fruits = ['mango', 'litchi',  'apple']
for index in range(len(fruits)):
   print 'Current fruit :', fruits[index]

print "Last line!"

Results

Current fruit : mango
Current fruit : litchi
Current fruit : apple
Last line!

Using else Statement with Loops

You can also run an else statement associated with a loop statement

  • If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.

  • If the else statement is used with a while loop, the else statement is executed when the condition becomes false.

#!/usr/bin/python

for num in range(10,20):  #to iterate between 10 to 20
   for i in range(2,num): #to iterate on the factors of the number
      if num%i == 0:      #to determine the first factor
         j=num/i          #to calculate the second factor
         print '%d equals %d * %d' % (num,i,j)
         break #to move to the next number, the #first FOR
   else:                  # else part of the loop
      print num, 'is a prime number'

Result :

10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number

Python nested loops

Python programming language allows to use one loop inside another loop.

for variable in sequence:
   for another_variable in variable:
      statements(s)
   statements(s)

Similarly for while loop :

while expression:
   while expression_in_expression:
      statement(s)
   statement(s)

Example

#!/usr/bin/python

i = 2
while(i < 100):
   j = 2
   while(j <= (i/j)):
      if not(i%j): break
      j = j + 1
   if (j > i/j) : print i, " is prime"
   i = i + 1

print "Last line!"

Result : 

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
Last line!

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.

Control Statement Description

break statement

Terminates the loop statement and transfers execution to the statement immediately following the loop.

continue statement

Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

pass statement

The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

Python break statement

It terminates the current loop and resumes execution at the next statement. The break statement can be used in both while and for loops but, If you are using nested loops, the break statement stops the execution of the innermost loop and start executing the next line of code after the block.

break

Example :

#!/usr/bin/python

for letter in 'Python':
   if letter == 'h':
      break
   print 'Current Letter :', letter
  
var = 5
while var > 0:              
   print 'Current variable value :', var
   var = var - 1
   if var == 3:
      break

print "Last line!"

Result : 

Current Letter : P
Current Letter : y
Current Letter : t

Current variable value : 5
Current variable value : 4

Last line!

Python continue statement

The continue statement rejects all the remaining statements in the current iteration of the loop and moves the control back to the top of the loop.

Syntax

continue

Example : 

#!/usr/bin/python

for letter in 'Python':     # First Example
   if letter == 'h':
      continue
   print 'Current Letter :', letter

var = 5                    # Second Example
while var > 0:              
   var = var - 1
   if var == 3:
      continue
   print 'Current variable value :', var

print "Last line!"

Result : 

Current Letter : P
Current Letter : y
Current Letter : t   #next h will be skipped
Current Letter : o
Current Letter : n

Current variable value : 4 #next 3 will be skipped
Current variable value : 2
Current variable value : 1
Current variable value : 0

Last line!

Python pass Statement

The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet.

Syntax : 

pass

Example : 

#!/usr/bin/python

for letter in 'Python': 
   if letter == 'h':
      pass
      print 'This is passed section'
   print 'Current Letter :', letter

print "Last line!"

Result 

Current Letter : P
Current Letter : y
Current Letter : t
This is passed section
Current Letter : h
Current Letter : o
Current Letter : n

Last line!

 


Loading ...

Related Results :

  1. For & While Loops
  2. Python Loop
Note :
  • Related Posts are generally User Blog posts.
  • or Other tutorials from other networks of w3clan.com.
  • Any registered user can create related posts based on search term tags.

About the Author