×

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

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Python program to convert Celsius into Fahrenheit

Python program to convert Celsius into Fahrenheit This program explains how we can take the temperature in Celsius and convert them into Fahrenheit. Celsius Celsius, also known as centigrade, is a measurement unit...

1 minute 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 Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Python String Variable

Python programming language: 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...

4 minutes read.

Uint8 Python

Python: 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 is said...

3 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 Logical Operators

In python, there are many operators which we use in our program. Operators are used in manipulating a particular value or operand. Logical operators are used mainly to evaluate an...

7 minutes read.

Spark and Python for big data with pyspark github

Pyspark: Apache Spark is a computational engine that handles large data sets using parallel and batch processing. Apache Spark is an open-source, distributed computing framework and collection of libraries for real-time,...

3 minutes read.

Check if a String is Empty in Python

The string is one of the data types of Python. This data type stores all kinds of data but all the characters must be enclosed using double quotes (""). In...

5 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Python tokens and character set

In this tutorial, we will understand what are character sets used in python and what is meant by python tokens and we will further discuss the type of tokens being...

4 minutes read.

__GETITEM__ and __SETITEM__ in Python

These methods are used in assignment operations, unary comparison operations, binary comparison operations and binary operations. These are pre-defined methods that perform many operations on a class instance. Examples like...

3 minutes read.

Google Chrome API 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....

3 minutes read.

Python print() function

Python print() function The print() function prints the specified message to the screen or other standard output devices. Syntax print(*objects,sep=' ',end='\n',file=sys.stdout,flush=False) Parameter objects: This function represents an object, which will be converted to a string...

1 minute read.

Python String rsplit() method

Python String rsplit() method The string.rsplit() method in Python splits a string into a list, starting from the right. If the "max" parameter is not specified, this method will return the...

1 minute read.

Python Project Ideas Based On Django

Introduction If you have learned Python and you are an expert in Django, then your practical skills should be excellent in this field. If you want to check your practical skills,...

9 minutes read.

What is Python compiler GDB?

The source code of one programming language is converted into machine code, bytecode, or another programming language by a compiler, a specialised software. A compiler is a tool that converts high-level...

3 minutes read.

Pillow Python introduction and setup

Introduction Advanced image processing implies handling the picture carefully with the assistance of a PC. Utilizing picture handling we can perform activities like upgrading the picture, obscuring the picture, separating text...

4 minutes read.

Python | a += b is not always a = a + b

a += b in Python doesn't always behave the same way as a = a + b; the same operands can produce different outcomes depending on the circumstances. But we...

3 minutes read.