Home > Programming > Loops in python illustrated

Loops in python illustrated


In python loops are very easy to use, if you know already while, for in C or Java those are almost similar in Python. The amount of code that we have to write in Python is much lesser when compared to many other languages, so its easier and saves a lot of time.

Ex1: In this example I’m using the “for” loop and “list”. You may be scared of what a list is. List is pretty similar to array in C or Java with many other built in function. Let us take a look at these things at work.

numbers=[]
i=1
while i<10:
    print "i above %d" %i
    numbers.append(i)
    print "number now is:", numbers
    i=i+1
    print "i below is %d" %i

Output

i above 1
number now is: [1]
i below is 2
i above 2
number now is: [1, 2]
i below is 3
i above 3
number now is: [1, 2, 3]
i below is 4
i above 4
number now is: [1, 2, 3, 4]
i below is 5
i above 5
number now is: [1, 2, 3, 4, 5]
i below is 6
i above 6
number now is: [1, 2, 3, 4, 5, 6]
i below is 7
i above 7
number now is: [1, 2, 3, 4, 5, 6, 7]
i below is 8
i above 8
number now is: [1, 2, 3, 4, 5, 6, 7, 8]
i below is 9
i above 9
number now is: [1, 2, 3, 4, 5, 6, 7, 8, 9]
i below is 10

The above same thing is achieved using for loop as

numbers=[]
for i in range(1,10):
    print "i above %d" %i
    numbers.append(i)
    print "number now is:", numbers
    i=i+1
    print "i below is %d" %i

range(1,10) assigns “i” to values “1 to 9”, by default the increment is 1 in the range function. If you want to increment the range value by 2. You have to give the syntax as range(1,10,2) which assings i to values 1,3,5,7,9

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: