For Loop In Python








In Python, a for loop is used to iterate over a sequence of items, such as a list, tuple, string, or other iterable objects. It allows you to execute a block of code for each item in the sequence.

The basic structure of a for loop in Python:

for item in iterable:

# Code to be executed for each item


Let's break down the components of a for loop:for: This keyword indicates the start of the loop.
item: This is a variable that represents the current item in the sequence during each iteration.
in: This keyword is used to specify the sequence you want to loop through.
iterable: The iterable object, like a list, string, or range, contains the items you want to iterate over.
Colon :: The colon is used to indicate the beginning of the loop body.

Example of a simple for loop that iterates through a list of numbers and prints each number:

numbers = [1, 2, 3, 4, 5]

for num in numbers:

print(num)

In the above example, the loop iterates through each element in the numbers list, and the num variable takes on the value of each element in turn. The print(num) statement is executed for each item in the list, resulting in the numbers 1 to 5 being printed.


Result:


Lets look few more examples:





Lets also see how to loop in range:




Conclusion:
You can use for loops to perform various operations on sequences, like searching for specific elements, calculating values, or processing data. The loop continues until it has iterated over all items in the sequence.
















Vijay Kashyap Algo Trading Expert

Author & Editor

Has laoreet percipitur ad. Vide interesset in mei, no his legimus verterem. Et nostrum imperdiet appellantur usu, mnesarchum referrentur id vim.