×

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

Assertion error in python

In this article, we will discuss assertions in the python programming language. Assertion: Assertions are a way of telling a program to test a certain condition and trigger an error if the...

3 minutes read.

List Assignment Index out of Range in Python

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

3 minutes read.

Sort Dictionary in Python

Dictionaries In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value. Dictionary contains key:...

4 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 program to find whether a given number is even or odd

Python program to find whether a given number is even or odd A number is said to be even if any number is completely divisible by 2, which means there is...

1 minute read.

Python Deep Copy and Shallow Copy

Assignment statements in Python create bindings between a target and an object, not copies of them. The = operator only makes a new variable that shares the reference to the...

3 minutes read.

Python Dictionary

Dictionary in Python is an unordered collection of data values, which is used to store data values like a map. Unlike different data types that hold just individual assets as...

4 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

How to check if the dictionary is empty in Python?

What is a dictionary in Python? A directory is a collection of data but data is not ordered. Unlike other data types, it does not hold a single value as its...

3 minutes read.

Recursive Multiplication Python

Recursive Multiplication Python In this tutorial, we will learn how to write a Python program to get the multiplication of two numbers using the recursive approach. In the recursive multiplication approach, we...

2 minutes read.

Word frequency Python

Word frequency Python In this tutorial, we will write the Python program to count the occurrence of a word (word frequency) in a given sentence. We will learn all the approaches...

5 minutes read.

Android apps for coding in python

Nowadays, it is the generation of smartphones. The world can be seen and acknowledged with a single click on your mobile phone. Everyone uses mobile phones to do any work,...

9 minutes read.

Python Set issuperset() method

Python Set issuperset() method The set.issuperset() method in Python returns a boolean value True if all items in the specified set exists in the original set, else it returns False. Syntax set.issuperset (set1) Parameter set- This parameter represents the...

2 minutes read.

Executing Shell Commands in Python

This tutorial aims to make us understand what a Shell is, what is the importance of a Shell, what are Shell commands in Python, and how can we execute the...

3 minutes read.

Notepad++ For Python

In this article, you are going to learn what notepad++ is and how it is integrated with python to use the python programming language. You can also learn how to...

4 minutes read.

Create a Table Using Tkinter in Python

Tkinter: The standard Python technique for building Graphical User Interfaces (GUIs) is Tkinter, which is included in all popular Python distributions. The only framework included in the Python standard library is...

3 minutes read.

Python random.seed() function

The random module in Python produces a random number or pseudo-random data, that is, deterministic. The seed function records the state of a random function to provide the same random...

6 minutes read.

Python BytesIO

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.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

Python Network Programming

In network programming, python plays a very important role. Python provides full support for encoding and decoding data and network protocol in its standard library. Writing a network program in...

3 minutes read.