For Loops in Python

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:

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

Code Example

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:

Output

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

Code Example:

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

Output

For Loop With Else

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

Code Example

Output

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

Please follow and like us:
Pin Share