Python for loop is used to iterate over a list of elements or strings. Today we will look into python for loop and it’s usage with some example programs. For loop is present in almost all programming languages and used a lot for iteration, same is the case with python for loops too. In the previous tutorial, we learned about python if else.
Python for loop
Python for loop is used to iterate over a list, tuple or strings. If you don’t know about list or string, you can learn it from Python Data types. The basic structure of Python for loop is given below.
for itarator_variable in sequence_name: Statements . . . Statements
For example, suppose we have a word, we need to print each letter of that word. So we can use python for loop as shown below.
word="anaconda" for letter in word: print (letter)
Again, you can use for loop to access a List data. Following code can help to understand the thing.
words= ["Apple", "Banana", "Car", "Dolphin" ] for word in words: print (word)
Python Nested For Loop
You can also write one for loop in between another for loop. But in this case, you have to maintain the indentation properly. The following code will illustrate python nested for loop.
words= ["Apple", "Banana", "Car", "Dolphin" ] for word in words: #This loop is fetching word from the list print ("The following lines will print each letters of "+word) for letter in word: #This loop is fetching letter for the word print (letter) print("") #This print is used to print a blank line
That’s all about python for loop examples. Hope that you learn well. For any query, feel free to ask in comment section. And must not forget, “Practice makes a man perfect”.