Loop constructs – for
The for loop is another control flow statement in programming languages that allows you to iterate over a sequence of values and execute a block of code for each value in the sequence.
The syntax of the for loop varies slightly depending on the programming language, but the basic structure is as follows:
for variable in sequence:
# code to execute for each value in the sequence
In this syntax, variable
is a variable that takes on the value of each element in the sequence
one at a time, and the block of code inside the loop is executed for each value of variable
.
Here is an example of a for loop in Python that prints the numbers from 1 to 5:
for num in range(1, 6):
print(num)
In this example, the range(1, 6)
function generates a sequence of numbers from 1 to 5 (inclusive), and the for
loop iterates over each value in the sequence one at a time, assigning it to the num
variable. The print
statement inside the loop prints the value of num
for each iteration of the loop.
The for
loop can be used to iterate over many different types of sequences, including lists, tuples, and strings, as well as other types of iterable objects.
Apply for PHP Certification!
https://www.vskills.in/certification/certified-php-developer