For loop

What is For loop in Python?
  • A for loop in python has the ability to iterate over items of any sequence (List, tuple, string) or any other iterable objects.
  • Iterating over a sequence is called traversal.
Syntax:
                    for var in sequence:
                            body statements
    
  • Here, var is a variable that is used to take the next values from the sequence on every iteration until the end of the sequence is reached.
  • Body statements of the for loop is separated from the rest of the code using indentation [tab].
Example:

For loop - example 
Output
range() function:
  • range() function is used to generate a sequence of whole numbers starting from 0 by default, increments by one, and ends at the specified number (n-1).
  • range(n) ex., range(6) will generate numbers from 0 to 5 (6 numbers).
  • We can also specify the starting number as well as the ending number by defining the range as range(start, stop).
  • range(start, stop) ex., range(5,9) will generate numbers from 5 to 8.
  • It is also possible to change/specify the increment value by adding a third parameter step_size, range(start, stop, step_size).
  • range(start, stop, step_size) ex., range(1,8,2) will generate numbers 1, 3, 5, 7.
range() function
Iterating by sequence index:
  • We can also use the range() function with len() function in for loop to iterate through a sequence using indexing.
Iterating through the sequence using indexing
Output
For loop with Else:
  • In Python, a 'for' loop can have an optional 'else' block.
  • The 'else' block will be executed only if all the iterations of the 'for' loop is completed.
For loop with Else block
Output
Nested for loop:
  • A 'for' loop inside an another 'for' loop is called nested for loop.
  • The inner 'for' loop will be executed at one time for each iteration of the outer 'for' loop.
Nested For loop
Output

No comments:

Post a Comment

You might also like

Deploy your Django web app to Azure Web App using App Service - F1 free plan

In this post, we will look at how we can deploy our Django app using the Microsoft Azure app service - a free plan. You need an Azure accoun...