Python For Loop
In this tutorial you'll learn how a count controlled for loop works in Python.
In Python, the for statement is designed to work with a sequence of data items (that is either a list, a tuple, a dictionary, a set, or a string).
The for loop is typically used to execute a block of code for certain number of times.
The for loop
The body of the loop is executed once for each item in the sequence.
for number in [1, 2, 3, 4, 5]: print("Python")
Python Python Python Python Python
The range Function with for Loop
The range() function creates a type of object known as an iterable to simplifies the process of writing a count-controlled for loop. The range() function returns a sequence of numbers, which starts from 0, increase by 1 each time the loop runs and ends at a specified number.
for number in range(5): print("Python")
The range with start and increment
With range() function it is possible to specify the starting value by adding second parameter and increment value by adding third parameter.
# Starts with 5 upto 9 for number in range(5, 10): print(number) # Starts with 5 upto 30 increment by 3 for number in range(5, 30, 3): print(number)
Looping Over Data Types
You can iterate list, dictionary or tuple items by using a for loop.
testList = ["Canada", "Japan", "London", "Germany", "Africa"] for item in testList: print(item) theDictionary = {'Canada': 100, 'Japan': 200, 'Germany': 300, 'Italy': 400} for item in theDictionary: print(item) thetuple = ("India", "Canada", "Japan", "Italy") for item in thetuple: print(item)