FOR LOOP
FOR LOOP
In Python, a for loop is used to iterate over a sequence (such as a list, tuple, string, or range) or any iterable object. The loop iterates over each item in the sequence and executes a block of code for each iteration. The general syntax of a for loop in Python is as follows
Here's a breakdown of each part:
In this example,
variableis a placeholder representing the loop variable that will take on each value from thesequenceduring each iteration of the loop. The loop will continue executing the code block until it has processed all the elements in thesequence.Let's see a specific example in Python where we use a for loop to print the numbers from 1 to 5:
EXAMPLE CODE:
for i in range(1, 6): print(i)
OUTPUT:
1
2
3
4
5
In this example,
range(1, 6)generates a sequence of numbers from 1 to 5 (inclusive). During each iteration, the loop variableitakes on the next value from the sequence, and theprint(i)statement outputs the value ofito the console.You can customize the behavior of a for loop based on your requirements. The sequence can be a range of numbers, a list, a string, or any iterable object depending on the programming language you are using.
Comments
Post a Comment