The for loop in Python is used to iterate over a sequence (list, tuple, string) or other iterable objects. Iterating over a sequence is called traversal.

Syntax of Loop

Here, val is the variable that takes the value of the item inside the sequence on each iteration. Loop continues until we reach the last item in the sequence. The body of for loop is separated from the rest of the code using indentation.

Flowchart of Loop

Flowchart of for Loop in Python programming

 

Example: Python Loop

Output

The range() function

We can generate a sequence of numbers using range() function. range(10) will generate numbers from 0 to 9 (10 numbers). We can also define the start, stop and step size asrange(start,stop,step size). step size defaults to 1 if not provided. This function does not store all the values in memory, it would be inefficient. So it remembers the start, stop, step sizeand generates the next number on the go. To force this function to output all the items, we can use the function list().

The following example will clarify this.

We can use the range() function in for loops to iterate through a sequence of numbers. It can be combined with the len() function to iterate though a sequence using indexing. Here is an example.

Output

for loop with else

A for loop can have an optional else block as well. The else part is executed if the items in the sequence used in for loop exhausts. break statement can be used to stop a for loop. In such case, the else part is ignored. Hence, a for loop’s else part runs if no break occurs.

Here is an example to illustrate this.

Output 1

Output 2

Here, we have a list of digits from 0 to 6. We ask the user to enter a digit and check if the digit is in our list or not. If the digit is present, for loop breaks prematurely. So, the else part does not run. But if the items in our list exhausts (digit not found in our list), the program enters the else part.

LEAVE A REPLY

Please enter your comment!
Please enter your name here