For Loop in Python
The “for” loop in Python is used in cases for iteration of sequences. This can be a list, string dictionary, set, and tuple. The for loop is similar to the keyword in other programming languages. It functions like an iterator method that we can see in other object-oriented programming languages.
A for loop is one of the most sought after control statements in a Python program. You can use it when you are aware of the total sum of iterations needed for execution.
The syntax of for loop is not vague and can assist you in iterating through varied types of sequences. This loop needs at least a couple of variables to function.
The for loop in Python begins with the keyword “for” followed by an arbitrary variable name.
Syntax:
for iterator_var in sequence:
statements(s)
Python lets to apply the else statement with the for loop which can be applied only when the iterations are fully used. If the for loop has any of the break statement, then the else statement will not be executed.
Example Program:
For var in list(range(5)):
print(var)
for letter in’Python’:# traversal of a string sequence
print(‘Current Letter :’, letter)
print()
fruits =[‘banana’,’apple’,’mango’]
for fruit in fruits:# traversal of List sequence
print(‘Current fruit :’, fruit)
fruits =[‘banana’,’apple’,’mango’]
for index in range(len(fruits)):
print(‘Current fruit :’, fruits[index])