The for loop
The for loop in Python is a loop statement that allows you to execute a block of code a specific number of times, or over a sequence of items such as a list or a string. The syntax of the for loop is as follows:
yaml
for variable in sequence:
# code to be executed for each item in the sequence
The for loop will iterate over each item in the sequence, and the variable will be set to the value of the current item for each iteration. The code inside the block will be executed once for each item in the sequence.
Here is an example of using the for loop to print out the items in a list:
css
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
print(fruit)
This will output:
apple
banana
cherry
It is important to note that the sequence can be any iterable object, such as a list, tuple, dictionary, or string. In the case of a string, the for loop will iterate over each character in the string.
You can also use the range function to generate a sequence of numbers to iterate over. For example:
scss
for i in range(1, 6):
print(i)
This will output:
1
2
3
4
5 You can also use the break and continue statements inside a for loop to break out of the loop or skip certain iterations based on certain conditions, just like in the while loop.
Apply for Python Certification!
https://www.vskills.in/certification/certified-python-developer