Skip to content

Python For Loops Tutorial with Example

  • by

Python For Loops: for loop is used for iterating over a sequence, it can be either a list, tuple, or stringFor loop normally iterates through a list of objects and applies some methods or functions or operations over each of these objects.

Python For Loops Tutorial with Examples

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>:

Simple Python For Loop Example :

This is the simplest example code of python for loops.

languages = ["Java", "C++", "Perl", "Python"]
for x in languages:

Output: Java

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):

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)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All Examples of For Loops are in Python 3, so it may change its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *