Python For Loops: A for loop is used for iterating over a sequence, it can be either a list, tuple, or string. For loop normally iterates through a list of objects and applies some methods or functions or operations over each of these objects.
When do I use for loops?
Python for loops is typically used when we have a block of code, where you want to repeat a fixed number of times.
The array that the for loop iterates through is not necessarily a list. It can be a tuple. Sometimes it can be a dictionary. It can even be a string so every object is made of other simpler objects.
Python For Loops Syntax :
for <variable> in <sequence>: <statements>
Simple Python For Loop Example :
This is the simplest example code of python for loops.
languages = ["Java", "C++", "Perl", "Python"] for x in languages: print(x)
Output: Java
C++
Perl
Python
The for loop doesn’t require an index variable to set before the event, as the for the command itself allows for this.
range() Function
The range()
the function returns a sequence of numbers, where its starts from – 0 by default and increments by 1. And Finish at a specified number (last number ). See this example.
for x in range(5): print(x)
Output : 0
1
2
3
4
Do comment if yo have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All Examples of For Loops are in Python 3, so it may change its different from python 2 or upgraded versions.