Python Flow Control

Python for Loop

When programmers write a certain piece of code, loops allow them to condense hundreds of lines of code into a few simple lines. Loop statements allows them to write the code once and then execute a set of statements multiple times and reuse it as needed, increasing the likelihood that the program will function as planned. Python for loop is one such looping statement provided by the Python programming language.

Definition

  • Python for loop is a type of loop which is used to iterate a set of statements multiple times.
  • The Python for loop is used for sequential traversal of data structures or other iterable objects until the condition is satisfied.

Python for Loop

The for loop is very commonly used in Python programming because it saves coding time as well as makes the code efficient and easy to read. We use Python for loops for iterating a set of statements, data structures, or iterable objects.

Syntax

                    

for iterating_var in seq :
     statements(s)     # body of for loop

where,

iterating_var = variable that takes each individual value of seq in each iteration

seq = data structures like lists, strings, tuples, dictionary, set, range

statements = executable code

Flowchart

Python for loop flowchart

Let us understand the syntax and the flowchart clearly. Every item of the sequence is assigned to the iterating variable and then the set of statements is performed on it. This keeps on continuing in sequence until the condition inside the loop is met o the entire sequence has been exhausted.

Example

                    

cars = ['BMW', 'Audi', 'Tata', 'Ford']
for n in cars:
    print('Car Company:', n)

num = [1, 3, 5, 7, 9]
sum = 0

for i in num:
    sum = sum + i
print('The sum is:', sum)

Output

                    

Car Company: BMW
Car Company: Audi
Car Company: Tata
Car Company: Ford
The sum is: 25

Iterating by Sequence Indexing

Another method of iterating through each item is to use an index offset in the sequence. It is also possible to iterate using the sequence’s index. The fundamental concept is to first calculate the list’s length by using the len() function, and then loop over the sequence within that range using the range() function.

Example

                    

cars = ['BMW', 'Audi', 'Tata', 'Ford']

for index in range(len(cars)):
     print('Car Company:', cars[index])

Output

                    

Car Company: BMW
Car Company: Audi
Car Company: Tata
Car Company: Ford

The range() function

Python range() function is used to generate a series of sequential numbers as well as to iterate through a loop for a fixed number of times. The loop will be executed until the specified number in the range() function does not end.

Syntax

                    

range(start, stop, step_size)

where,

start = indicates the start of the iteration.

stop = indicates that the loop will continue until it reaches stop-1. It is optional.

step size = used to skip the iteration’s specific numbers. It’s entirely up to you whether or not you want to use it. The step size is set at 1 by default.

Note – If a single argument is passed to the range() function, then it will start those range of numbers starting from 0. If the range(5) is specified, then the range of values is from 0 to 4.

Example 1

                    

# To print a range of numbers
for i in range(6):
    print('Number:', i)

Output

                    

Number: 0
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Example 2

                    

# print values of list using range() in for loop
students = ['Rock', 'John', 'Tia', 'Jenny', 'David'] 
for name in range(len(students)): 
    print("Welcome", students[name])

Output

                    

Welcome Rock
Welcome John
Welcome Tia
Welcome Jenny
Welcome David

Python for loop with else

The else keyword specifies a block of code that can be used along with the for loop which indicates when the for loop finishes executing the items in the sequence, this block of code will be executed next. After all the iterations of for loop have been completed, the else statement will be executed.

Example 1

                    

for n in range(0, 5):
        print('Numbers are:', n)
else:
    print('No items left')

Output

                    

Numbers are: 0
Numbers are: 1
Numbers are: 2
Numbers are: 3
Numbers are: 4
No items left

Example 2

                    

dislike_choice = 'Worst'
genre = {'Good': 'rock', 'Good': 'jazz', 'Bad': 'reggae', 'Better': 'house', 'Best': 'pop', 'Best': 'hiphop'}

for s in genre:
    if s == dislike_choice:
        print('I do not like:', genre[s])
        break
else:
    print('Worst genre not found')

Output

                    

Worst genre not found

Nested for loop

Python allows us to nest for loop inside another for loop. For each iteration of the outer loop, the inner loop will be executed n number of times. Unless the outer loop iteration does not end, the inner loop iterations will keep executing.

Example

                    

rows = int(input('Enter no. of rows: '))

for i in range(rows+1):
    for j in range(i):
        print('*', end = '')
    print()

Output

                    

Enter no. of rows: 7
*
**
***
****
*****
******
*******

Frequently Asked Questions

Q1. What is a for loop in Python?

Statements are usually executed in the order in any programming language: the first statement in a function is executed first, then the second, and so on. You may find yourself in a position where you need to run a block of code multiple times. Different control structures are available in programming languages, allowing for more sophisticated execution routes.

Python provides us with a loop statement called a for loop. A Python for loop is a type of loop which is used to iterate a set of sequential statements multiple times. In for loop every item of the iterable (list, tuple, string, dict, set) is assigned to an iterable variable. Then a set of statements are performed for each item assigned to the iterable variable until the sequence has been exhausted.

Q2. How do you write a for loop in Python?

The syntax for writing for loop in Python is –

                    

for iterating_var in seq :
       statements(s)   # body of for loop

where,

iterating_var = variable that takes each individual value of seq in each iteration

seq = data structures like lists, strings, tuples, dictionary, set, range

statements = executable code

Example

                    

items = ['bread', 'butter', 'cheese', 'sauce', 'eggs', 'tea powder']

print('Shopping List Items:')
for n in items:
    print(n)

Output

                    

Shopping List Items:
bread
butter
cheese
sauce
eggs
tea powder

Q3. What are the 3 types of loops in Python?

Python programming language provides us with 3 types of loops. They are –

  1. for loop – A Python for loop is a type of loop which is used to iterate a set of sequential statements multiple times.
  2. while loop – Python while loop allows the program to execute a statement or a set of statements for TRUE condition. The statement will continue to be executed until the condition becomes FALSE.
  3. Nested loop – Nested loop allows the functionality to the programmer to nest one or more for or while loops inside of each other. The inner loop will be executed until the outer loop doesn’t get exhausted.

Q4. Is there a repeat function in Python?

Yes, there is a repeat() function in Python. In the repeat() function, we specify the data and the number which will repeat that many times. But for this function to be used, we need to import the itertool module. Itertool is a Python package that has a number of functions that work with iterators to create complicated iterators. Infinite iterators are represented by itertools.repeat().

Syntax

                    

repeat(value, number)

Example

                    

# Python code to demonstrate the working of repeat()
import itertools

# using repeat() to repeatedly print a word
print("Printing the word repeatedly : ")
print(list(itertools.repeat('Hello', 5)))

Output

                    

Printing the word repeatedly :
['Hello', 'Hello', 'Hello', 'Hello', 'Hello']

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

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

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.