×

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.

Python String Methods

Python String Methods Python has a set of built-in string methods. The Python string methods are as follows: capitalize() The string.capitalize() method returns a copy of the string by converting the...

5 minutes read.

Difference between Perl and Python

Control and presently utilized for a great many undertakings, including framework organization, web improvement, network programming, and GUI improvement, and the sky is the limit from there. About Perl? Perl is a...

4 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Features of Python

Python is a powerful, easy to learn, popular programming language. It has effective data structures and its elegant syntax makes it user-friendly language. Below are the key features of Python: 1. Python...

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

Python Bubble Sort

Bubble sort is one of the techniques used to sort the elements in lists in a certain order, either in ascending or descending order. It is called Bubble sort because...

4 minutes read.

Python NewLine

In python, a new line character denoted by "\n" is known as an escape character or escape sequence, and it will force the cursor to change its position to the next...

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

How to run Python code from the command prompt

The Windows operating system's command-line interpreter is CMD or Command Prompt. The "MS-DOS Prompt" is comparable to Command.com, used in DOS and Windows 9x computers. It is similar to Unix...

3 minutes read.

Python sort() function

Python provides many built-in functions for solving many problems that arise in different situations in programs. One of such methods is the sort () method. In this article, the syntax...

4 minutes read.

Python elif

Python elif The elif statement is used to check multiple conditions and execute the specific block of statements depending upon the true condition among them. Syntax if expression1: statement elif expression2: statement elif expression3: statement else: statement The elif statement can be optional...

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.

Best app for python

What is python? Python is a prevalent, general-purpose, and high-level programming language. Python Programming Language is appropriate for experienced programmers and also for beginners. Python programming language is being utilized by...

19 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 for Data Analysis

Data analysis uses various techniques to read, illustrate, manipulate and evaluate a particular data. You can have access to the data and keep the data updated regularly. You can append...

4 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

Alexa Python

The cloud-based voice assistant renders text into speech in a female voice. Alexa is a virtual assistant released by Amazon. Using itself as a system for home automation, Alexa can...

4 minutes read.

Python filter() function

Python filter() function The filter() function constructs an iterator from those elements of iterable for which the parameter ‘function’ returns a Boolean value true. Syntax filter(function, iterable) Parameter function: This parameter represents a function to be run for each item in the...

1 minute read.

Python Matrix Multiplication

One of the most fundamental mathematical structures, matrices are used often in many disciplines, including mathematics, physics, engineering, computer science, etc. For example, matrices and associated operations (multiplication and addition) are...

8 minutes read.