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)
The for loop doesn’t require an index variable to set before the event, as the for the command itself allows for this.
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
Do comment if yo have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Examples of For Loops are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.