Loops in Python

Loops are we much useful to do a repeated set of work.For example, consider printing 1 to 10. In order to print without using loops we need to write the print statement 10 times.If we need to print 100 numbers,then it can be some irksome task.With the help of loops we use print any number of numbers by writing a single print statement.

Every Programming language contains For,While and do..while loops.But python do not support do..while loop but we can implement it in different way.In this tutorial we are going to teach you the basic syntax for using for and while loops.

For loop: Comparing to other loop statements for loop is more handy,because we can initialize,check the condition,increment/decrement the loop variable in a single line.Before we learn about for loop we need to learn range() function in python. range() is used to specify the limit.If range(6),then it starts from 0 to 5.If range(1,6) then it starts from 1 and ends at 5.If range(1,6,2) then the limit is 6/2=3.
The basic syntax for using for loop is:

for x in range(limit) :
   print x

Explanation:Now the x value will be initialized with 0 and it ends with n-1 value.These values will be printed using print method.
While Loop:It is also called as entry controlled loop.If the condition is true then only the statements present in it are executed.
The basic syntax of while loop is

while(condition) :
    <true statements>

Explanation:If the condition is satisfied then only the true statements in the while loop will be executed.

Advertisements

About Anuroop D

Very enthusiastic about technology and likes to share my knowledge through blogging. Has Bachelor's in Information Technology and currently pursuing my Master's in Computer Science.
This entry was posted in Python and tagged , , , , , , , , , , , , , , , , . Bookmark the permalink.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s