This tutorial explains Python for loop, and its syntax and provides various examples of iterating over different sequence data types. For loop is the most common control flow statement used by programmers for performing repetitive tasks. The best case to use it is when you know the total no. of iterations required for execution.
Python For Loop Definition, Syntax
Python provides a simple and straightforward syntax to use “for loop” in programs. It can help you iterate through different types of objects. Python supports seven sequence data types: standard/Unicode strings, a list, tuples, a byte array, and xrange
objects. There are sets and dictionaries as well, but they are just containers for the sequence types.
A for loop in Python requires at least two variables to work. The first is the iterable object such as a list, tuple, or string. And second, is the variable to store the successive values from the sequence in the loop.
Python For Loop Syntax
In Python, you can use the “for” loop in the following manner.
# syntax for iter in sequence: statements(iter)
The “iter” represents the iterating variable. It gets assigned successive values from the input sequence.
The “sequence” may refer to any of the following Python objects such as a list, a tuple, or a string.
For Loop Flowchart
The for loop can include a single line or a block of code with multiple statements. Before executing the code inside the loop, the value from the sequence gets assigned to the iterating variable (“iter”).
Below is the For loop flowchart representation in Python:
Python For Loop Examples
Here is the code using Python for loop to print all characters of a string.
# Program to print the letters of a string using for loop vowels = "AEIOU" for iter in vowels: print("char:", iter) """ Output char: A char: E char: I char: O char: U """
Let’s now widen our logical thinking. Here is a step-by-step procedure to calculate the average of N numbers using a for loop in Python. We’ll use the following steps to compute the avg. of N numbers.
- Create a list of integers and populate it with N (=6) values.
- Initialize a variable (sum) for storing the summation.
- Loop N (=6) number of times to get the value of each integer from the list.
- In the loop, add each value with the previous and assign it to a variable named the sum.
- Divide the “sum” by N (=6). We used the len() function to determine the size of our list.
- The output of the previous step is the average we wanted.
- Finally, print both the “sum” and the average.
Below is the Python code for the above program.
# Program to calculate the average of N integers int_list = [1, 2, 3, 4, 5, 6] sum = 0 for iter in int_list: sum += iter print("Sum =", sum) print("Avg =", sum/len(int_list))
Here is the output after executing the above code.
""" Output Sum = 21 Avg = 3.5 """
Range() Function with For Loop
Python range() function returns a list or a sequence of numbers at runtime. For example, a statement like range(0, 10) will generate a series of ten integers starting from 0 to 9. The below snippet tries to show that range() returns a list and its elements are available via indexes.
# Check the type of list returned by range() function print( type(range(0, 10)) ) # <class 'range'> # Access first element in the range list print( range(0, 10)[0] ) # 0 # Access second element print( range(0, 10)[1] ) # 1 # Access last element print( range(0, 10)[9] ) # 9 # Caclulayte the size of range list print( len(range(0, 10)) ) # 10
Let’s now use the range() with a Python “for” loop.
for iter in range(0, 3): print("iter: %d" % (iter))
It will yield the following result.
""" Output iter: 0 iter: 1 iter: 2 """
By default, the for loop fetches elements from the sequence and assigns them to the iterating variable. But you can also make it return the index by replacing the sequence with a range(len(seq)) expression.
books = ['C', 'C++', 'Java', 'Python'] for index in range(len(books)): print('Book (%d):' % index, books[index])
The following lines will get printed.
""" Output Book (0): C Book (1): C++ Book (2): Java Book (3): Python """
Else Clause with Python For Loop
Interestingly, Python allows the use of an optional else statement along with the “for” loop.
The code under the else clause executes after the completion of the “for” loop. However, if the loop stops due to a “break” call, then it’ll skip the “else” clause.
Check the below syntax to use the else clause with Python for loop.
# Foe-Else Syntax for item in seq: statement 1 statement 2 if <cond>: break else: statements
Look at the below For Loop with Else flowchart to understand it more clearly.
Below is the sample code that uses a for loop and an else statement.
# Simple Python program to demonstrate the use of else with for loop birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow'] ignoreElse = False for theBird in birds: print(theBird ) if ignoreElse and theBird == 'Snow': break else: print("No birds left.")
The above code will print the names of all birds plus the message in the “else” part.
""" Output Belle Coco Juniper Lilly Snow No birds left. """
Setting the “ignoreElse” variable to “True” will get the “else” part ignored. And, only the names will get displayed.
Python For Loop Summary
In this tutorial, we explained the concept of Python for Loop with several examples so that you can easily use it in real-time Python programs. However, if you have any questions about this topic, please do write to us.
Also, if you found it useful, then do share it with your colleagues. Also, connect to our social media accounts to receive timely updates.
Best,
TechBeamers