Python
Python

How to use For Loop in Python

In previous articles, we had seen conditional statements, how to use them and some python programs based on conditional statements. Among the 2 loops available we will see python for loop in this article.

Python uses two loops.

  • for loop: It will execute the statement or group of statement till the value of the variable.
  • while Loop: While loops repeat a statement or group of statements when the given condition is TRUE. It will terminate when the condition is false. Before running the statements it tests the condition for the condition.

When we use multiple for and while loops within one for or while loop we call them as nested loops.

Let us see for loop in this article.

Basic Syntax:

for obj in range() : or any collection

  body 

else:             #Here else condation is optional

Python is the first language that allows else condition with for-loop but else is optional.

Here in for-loop, you have seen the : (colon), here the colon represents the start of the body. In python, we don’t have { } curly braces, in place of curly braces we use the (:) colon.

Example:

for x in range (10):
   print(x)

In the above code, we have seen the range, the range is the function which defines the start and endpoint of the loop, but here range function has the only endpoint, not the starting point is defined, if the starting point is not defined in that case range by default start from 0, for more detail about range function() you can click on more 

The above code will run 10 times from 0 to 9 as the range is defined 10.and it will print 1 to 9 counting.

output:

 

Example2:

for x in range (1,10):
  print(x)

Here in range function starting and the endpoint is defined, the loop will start from 1 to 9.

output:

Example3:

for x in range (1,10,2):
  print(x)

In the above program along with the starting and ending point the third parameter is defined, which is called a step.

A step is  An integer number specifying the incrementation. The default value of the step is 1.in the output you can see it the 2, 4, 6,8 are not displayed, because in steps it is print the incremented value.

output:

 

The output of the program is coming vertically what if you want output horizontally.

Example: 

for x in range(1,10):

  print(x,end='')

output:

if you want to separate them out by comma(,) you can separate it.

Example: 

for x in range(1,10):

  print(x,end=' ,')

Leave a Reply