×

Python for loop

 Python for loop

A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other programming language like C or Pascal. It is used to traverse the Python data structure like list, dictionary, or tuple.

Syntax

for iterating_var in sequence: 
   statements

If a sequence holds an expression list, it is evaluated first. Then, the first item in the sequence is allocated to the iterating variable iterating_var. Then, the statements block is executed. Each item in the list is assigned to iterating_var; the statement block is executed until the entire sequence is terminated.

Python For Loop

Flow- diagram

In the above flow diagram, for loop iterate over the sequence. It takes the first element of the sequence and executes the statement block. It moves on the next item in sequence until no item left in the sequence.

Examples of for loop

1. Write a program to print the square of two number from a given list

list = [1,2,3,4,5] 
for e in list:
    print(e**2)

Output:

1
4
9
16
25 

2. Write a program to Character from a given string

str = 'Python'
for e in str:
    print(e)

Output:

P
y
t
h
o
n 

3. Write a program to find the sum of all number of given list

list = [25,42,32,12,33]
 sum = 0
 for e in list:
    sum = sum+e
 print("The sum is:",sum)

Output:

The sum is: 144

Iterating by Sequence Index

We can iterate the sequence through the index of the element. First, let’s understand the range function.

The range () function:

The range () function is used to iterate over a given sequence of numbers. Generally, it takes three arguments (stop and step are optional). Python provides flexibility to define range function according to our requirement. For example:

  • range(n)- Generate the numbers starting from start to n-1 range(5) will generate 0,1,2,3,
  • range(start,stop)- Generate a set of numbers starting from start to stop-1 range(1,10) will generate 0,1,2,3,4,5,6,7,8,9
  • range(start,stop,step)- We can generate numbers having difference of the given step-size . range(3,20,3) will generate  3,6,9,12,15,18

Example of for loop using range()

Write a program to find sum of first 1 to n natural number

n=int(input('Enter the number'))
# Define a variable to stored number for specific range
sum=0
for i in range(1,n+1):
#As we know range(n) will generate n-1 that’s why we assign n+1
#it will generate n+1-1 or n numbers
    sum=sum+i
# Sum of numbers stored in sum variable
print(sum)

Output:

Enter the number 50
1275

Write a program to check the given number is prime or not.

n = 12
# If given number n is greater than 1
if n>1:
# Iterate from 2 to n // 2
    for i in range(2, n // 2):
# If n is divisible by any number between 2 and n // 2, it is not prime
        if (n % i) == 0:
            print(n,"is not a prime number")
            break
        else:
            print(n, "is a prime number")
else:
    print(n, "is not a prime number") 

Output:

23 is a prime number

Python Nested for loop

If a for loop exists inside another for loop, then it is called Nested for loop. Nested for loop is best to use in pattern programming. For example:

1. Write a program to print stars in a triangle shape.

n = int(input("Enter the number of lines"))
# Take input for number of lines
for i in range(n):
#first for loop is using for print number of lines
    for j in range(i):
#second for lop is using for print star(*)
        print("*",end='')
     print() 

           Output:

Enter the number of lines :10
 *
 **
 ***
 ****
 *****
 ******
 *******
 ********
 ********* 

2. Write a program to find the prime number within a range

 
start = int(input("Enter the start range"))
stop = int(input("Enter the stop range"))
for n in range(start,stop+1):
# If given number n is greater than 1
    if n>1:
 # Iterate from 2 to n // 2
        for i in range(2,n//2):
# If n is divisible by any number between 2 and n //2, it is not prime
            if(n%i==0):
                break
            else:
                print(n)
 else:
  print("the number is not greater than 1")

Output:

Enter the start range:100
Enter the stop range:150
101
103
107
109
113
127
131
137
139
149

Using else statement with for loop

Python provides the optional ‘else’ statement associated with for loop. The ‘else’ statement executes only when the loop has completed all iteration. For example:

for i in range(6):
    print(i)
 else:
    print("Iteration is completed")

Output:

0
1
2
3
4
5 
Iteration is completed 

Related Topics

Inheritance in Python

Inheritance in Python Object-Oriented Programming provides reusable patterns to the code for restricting the redundancy in development projects. One of the basic principles of Object-Oriented Programming that helps achieve recyclable code...

8 minutes read.

Python Algorithms

A quote goes, "A goal without a plan is just a wish." To achieve anything in life, we can't simply go for it without making a plan and sticking to...

4 minutes read.

Introduction to Scratch programming

Scratch programming is generally designed for children who may create digital stories, games, and animations using the computer language Scratch, which has the largest kid-focused community in the world. Scratch...

3 minutes read.

Python Data Visualization

In this tutorial, we will understand what data visualization means in python. Further, we will see different methods of visualizing data in python. Data visualization In a non-technical language, it is a...

4 minutes read.

Python Time Module

Python contains many files that can be imported into a python code and used whenever we want. One of that modules is the time module. It is a good practice...

6 minutes read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Python Sys Stdout

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

3 minutes read.

tell() function in Python

Introduction The tell() function in Python is used to return the current position of the file read/write pointer within the file. An integer value is returned by this method, and it...

2 minutes read.

Python Lexicographic Order

Python lexicographic order Before we discuss the lexicographic order in Python, we should understandwhat is lexicographic order and sort according to lexicographic order. Lexicographic order In mathematics, the generalization of the alphabetical order...

5 minutes read.

Poolmanager in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

4 minutes read.

Palindrome In Python

What is Palindrome? A Palindrome can be defined as the number or a string that resides unchanged when it is reversed. Example: 14341 Output: Yes, this is a Palindrome number Example: RACECAR Output: Yes, this...

2 minutes read.

Create Table Using PyQt5 in Python

PyQt5: PyQt5 is one of several solutions that Python offers for creating GUI applications. Cross-platform GUI toolkit PyQt5 is a collection of Python interfaces for Qt version 5. With this library's...

4 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Python Set update() method

Python Set update() method The set.update() method in Python updates the current set, by adding items from another set. If an element is common in both the sets, only one appearance of this item...

1 minute read.

Python Project Ideas for Advanced Developers

Best Python Project Ideas for Advanced Developers Python is an object-oriented, high-level, interpreted programming language created by a developer known Guido Van Rossum. Python is one of the languages that gathered...

9 minutes read.

Python vars() Function

Python vars() Function The vars() function in Python returns the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute. Syntax vars([object]) Parameter object: This parameter represents any object with a __dict__attribute Return This function returns...

1 minute read.

Python Operator Precedence

Before knowing about the operator precedence in Python, we have to know about the operators in Python. So let's have a look at it. According to one definition, the operator is...

3 minutes read.

Python String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

How to Iterate a List in Python

As we know, a List is one of the four unique data structures available in Python; in this article, we will deep dive into understanding iterating through a list and...

3 minutes read.