DEV Community

pulkitgovrani
pulkitgovrani

Posted on

For Loops in Python

A for loop executes a sequence of statements many times till a particular condition is reached.
Let’s take an example: Assume that we will give food to a person 10 times so he will take food for 1st time, 2nd time, …… 10th time and then we will not give the food which results in breaking of the loop.

Syntax of For loop:

For Loop Syntax

The body of for loop is separated from the code using the indentation.

Code Example

For Loop Example

Output

For Loop Output

The range() Function

The range() function gives a sequence of numbers, by default starting from 0 ,and incrementing by 1(default) and ends at the given number. We can use range() function for looping through a sequence a certain number of times.
If we take range(5) then it returns 0,1,2,3,4 as values.
Note: range(5) returns the values from 0 to 4 and not 0 to 5.

Code Example:

For Loop range

Output

For Loop Range Output

The starting value of the range function is 0 by default but we can specify it by adding one more parameter.

Code Example:

Loop Range Specified

Output

Range Output

The incrementing value is 1 by default but we can specify it also by adding one more parameter but it is necessary to write starting index and ending index.

Code Example

Loop Range & Increment Specified

Output

Range & Increment Output

For Loop With Else

We can write an else statement with for loop it is executed when the loop stops executing.

Code Example

For Loop Else

Output

For Loop Else Output

I hope you were able to understand how for loop works in python.

Top comments (0)