×

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

Reverse a sentence In Python

Introduction The built-in reverse() function is not supported by the Python string library. As we know, a Python string is defined as a set of Unicode characters and Python provides various...

4 minutes read.

How to clear screen in Python?

How to clear screen in python There are times when we execute our program and it results in an unexpected output. The obtained result can contain some kind of garbage values...

4 minutes read.

Collections in python

In this tutorial, we will see what is collection in python.  Further, we will see in-depth the different kinds of collections in python. Collections Collections in python are the built-in module used...

9 minutes read.

Python SQLite

SQLite It is an RDBMS (Relational Database Management System). It is an embedded, serverless, transactional SQL database engine. It is an open-source application. It is named SQLite because of its lightweight....

3 minutes read.

Python MySQL Delete Operation

Python MySQL Delete Operation: Like the update operation where we were updating required field from a SQL table, we can also delete an entry from the table which we have...

4 minutes read.

Python Letter to Number

Python Letter to Number In this tutorial, we will convert the given letters into numbers using a Python. We will convert the given letter into the letter value as defined in...

3 minutes read.

Python comment symbol

Python programmers frequently use the comment system because, without it, things may quickly become very perplexing. The developers' helpful information is provided in the comments, which helps the reader understand...

3 minutes read.

Yield Statement In Python

The generators are defined by using the yield statement in Python. Generally, it converts a normal Python function into a generator.  The yield statement hauls the function and returns back the...

2 minutes read.

Calculator Program in Python

Simple Calculator Program in Python This example helps to learn how to create a simple calculator program to perform operations like addition, subtraction, multiplication, and division. Source Code The following is the source...

2 minutes read.

Cube Root in Python

In general, the cube is a three-dimensional solid figure that has 6 square faces. It is also called a geometrical shape with six equal faces, eight vertices, and twelve edges....

3 minutes read.

Slicing of a String in Python

In this tutorial, we will learn about slicing of a string in Python. First of all, let us know what String and Slicing is. String String is a group of characters that...

6 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.

Python divmod() function

Python divmod() function The divmod() function in Python returns a tuple containing the quotient  and the remainder when parameter ‘a’ (divident) is divided by parameter ‘b’ (divisor). Syntax: divmod(a, b) Parameter a: This parameter represents a number you...

1 minute read.

Python dir() function

Python dir() function The dir() function in Python returns all properties and methods of the specified object, without the values. Syntax dir([object]) Parameter object: This parameter represents the object one wants to see the valid attributes. Return This function...

2 minutes read.

Python IDE names

Python is one of the most renowned programming languages. It has different execution conditions and a great many compilers to execute the python programs, e.g., PyCharm, PyDev, Jupyter Notebook, Visual...

6 minutes read.

Python String endswith() method

Python String endswith() method The string.endswith() method in Python returns a Boolean value True if the string ends with the specified suffix, otherwise it returns False. Syntax endswith(suffix[, start[, end]]) Parameter suffix – This parameter represents a string or tuple...

2 minutes read.

How to Program in Python on Raspberry pi?

Introduction to Python A popular programming tool with simple, complete novice syntax is Python structure of paragraphs, phrases, and words. Due to its widespread use, this has a large community that...

4 minutes read.

Isodate Python

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.

Decision Tree Classification in Python

In this article, we will learn the implementation of the decision tree in Sklearn, which is nothing but the Scikit Learn library of python. First, we should learn what classification...

12 minutes read.

Struct Module in Python

What is a structure in Python? An entity that holds data in form of a structure is called a data structure. In Python, the data structure includes tuples, lists, dictionaries, and...

4 minutes read.