For Loop

Using for Loop and else statement. 
For Loop using range
Syntax of range is range(begin,end, step)

# Prints out the numbers 0,1,2,3,4
Example
for x in range(5):
 print(x)

# Prints out 3,4,5 increment by 1
Example
for x in range(3, 6):
 print(x)

# Prints out 3,5,7 increment by 2.
Example
for x in range(3, 8, 2):
 print (x)
Result




















Using for Loop with list.
Define fruits as list and get each element as fruit from list fruits.

Example
fruits = ['banana', 'apple',  'mango','orange']
counter=0;
for fruit in fruits:   
   counter +=1   
   print str(counter), fruit

Result


Nested for Loop – Define power of Number .
Define a for loop within a loop. If break statement is inside a nested loop (loop inside another loop), break will terminate the innermost loop.

Example
for x in xrange(1, 6):
    print ('power of %d'%x)
    for y in xrange(2, 4):
        print '%d power %d = %d' % (x, y, pow(x,y))

Result


Using for Loop and else statement. 
Loop till the condition is met and then execute else statement. The else clause 
executes when the loop completes normally. This means that the loop 
did not encounter any break. If break statement is inside a nested 
loop (loop inside another loop), break will terminate the innermost loop.
 
Example
for x in xrange(1,10,3):
    print x
   ß--------------- Break  # this will terminate and else will not execute.
else:
    print 'Final x = %d' % (x)

Result

Using for with string and print each letter from string.
Print each character from the string using index of string.

Example
string = "Good Morning"
print string
for x in string:
    print string.index(x),x

Result


Using break and continue in for Loop statement.
Example

for i in range(1,10):
   if i %2== 0:
        continue
   if i == 7:
        print 'break at',i
        break
   print i

Result

No comments:

Post a Comment