.

Tuesday, July 7, 2015

Python | For..Loop examples

In Python (v2.7), we have 2 type of loops - For and While

In this post, we printed few know series. These are not useful as is, in  your application but these are surely going to help you in building logical concepts using loops.


1. Right triangle using multiples of 5

for x in range(5,50,5):
    for y in xrange(5,x,5):
        print y,
    print ""















2. Right triangle from group of numbers

for x in range(3,15,3):
    for y in xrange(3,x):
        print y,
    print ""











3. Left triangle

for x in xrange(1,5):
    for y in xrange(1,5):
        if y < 4 - x + 1:
            print " ",
        else:
            print y,
    print ""





 4. Pyramid structure

for x in xrange(1,5):
    for y in xrange(1,8):
        if (y >= 5 - x and y <= 5 + x - 2):
            print (x+y)-4,
        else:
            print " ",
    print ""

No comments :

Post a Comment