0% found this document useful (0 votes)
8 views5 pages

Python For Loop Explained

The document provides an overview of the for loop in Python, explaining its syntax and how it can be used to iterate over various data types such as lists, tuples, strings, and dictionaries. It includes examples demonstrating the use of for loops with different data structures and the optional else statement that can be associated with loops. Additionally, it covers the range function for generating sequences of numbers for iteration.

Uploaded by

rvijistephen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views5 pages

Python For Loop Explained

The document provides an overview of the for loop in Python, explaining its syntax and how it can be used to iterate over various data types such as lists, tuples, strings, and dictionaries. It includes examples demonstrating the use of for loops with different data structures and the optional else statement that can be associated with loops. Additionally, it covers the range function for generating sequences of numbers for iteration.

Uploaded by

rvijistephen
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Home Whiteboard AI Assistant Online Compilers Jobs Tools Articles

Chapters Categories

SQL HTML CSS Javascript Python Java C C++ PHP Scala

Python - For Loops

The for loop in Python provides the ability to loop over the items of any sequence,
such as a list, tuple or a string. It performs the same action on each item of the
sequence. This loop starts with the for keyword, followed by a variable that
represents the current item in the sequence. The in keyword links the variable to the Python for Loop with Strings
sequence you want to iterate over. A colon (:) is used at the end of the loop header,
and the indented block of code beneath it is executed once for each item in the A string is a sequence of Unicode letters, each having a positional index. Since, it is a
sequence. sequence, you can iterate over its characters using the for loop.

Syntax of Python for Loop Example

The following example compares each character and displays if it is not a vowel ('a',
for iterating_var in sequence: 'e', 'i', 'o', 'u').
statement(s)
Open Compiler

Here, the iterating_var is a variable to which the value of each sequence item will
be assigned during each iteration. Statements represents the block of code that you zen = '''
want to execute repeatedly. Beautiful is better than ugly.
Explicit is better than implicit.
Before the loop starts, the sequence is evaluated. If it's a list, the expression list (if
Simple is better than complex.
any) is evaluated first. Then, the first item (at index 0) in the sequence is assigned to
Complex is better than complicated.
iterating_var variable.
'''
During each iteration, the block of statements is executed with the current value of for char in zen:
iterating_var. After that, the next item in the sequence is assigned to if char not in 'aeiou':

iterating_var, and the loop continues until the entire sequence is exhausted. print (char, end='')

Flowchart of Python for Loop On executing, this code will produce the following output −

The following flow diagram illustrates the working of for loop −


Btfl s bttr thn gly.
Explct s bttr thn mplct. total = 0
Smpl s bttr thn cmplx. for num in numbers:
Cmplx s bttr thn cmplctd. if num%2 == 0:
print (num)

Python for Loop with Tuples


When you execute this code, it will show the following result −
Python's tuple object is also an indexed sequence, and hence you can traverse its
items with a for loop.
34
54
Example 78
44
In the following example, the for loop traverses a tuple containing integers and 80
returns the total of all numbers.

Open Compiler Python for Loop with Range Objects


Python's built-in range() function returns an iterator object that streams a sequence
numbers = (34,54,67,21,78,97,45,44,80,19) of numbers. This object contains integers from start to stop, separated by step
total = 0 parameter. You can run a for loop with range as well.
for num in numbers:
total += num
Syntax
print ("Total =", total)
The range() function has the following syntax −

On running this code, it will produce the following output −


range(start, stop, step)

Total = 539
Where,

Python for Loop with Lists Start − Starting value of the range. Optional. Default is 0

Python's list object is also an indexed sequence, and hence you can iterate over its Stop − The range goes upto stop-1
items using a for loop. Step − Integers in the range increment by the step value. Option, default is 1.

Example
Example
In the following example, the for loop traverses a list containing integers and prints
In this example, we will see the use of range with for loop.
only those which are divisible by 2.

Open Compiler
Open Compiler

for num in range(5):


numbers = [34,54,67,21,78,97,45,44,80,19]
print (num, end=' ')
print()
Example
for num in range(10, 20): The following example illustrates the above mentioned approach.
print (num, end=' ')
print()
Open Compiler
for num in range(1, 10, 2):
print (num, end=' ')
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in numbers:
When you run the above code, it will produce the following output − print (x,":",numbers[x])

0 1 2 3 4
10 11 12 13 14 15 16 17 18 19 It will produce the following output −

1 3 5 7 9
10 : Ten
20 : Twenty
Python for Loop with Dictionaries 30 : Thirty
40 : Forty
Unlike a list, tuple or a string, dictionary data type in Python is not a sequence, as the
items do not have a positional index. However, traversing a dictionary is still possible
with the for loop. The items(), keys() and values() methods of dict class return the view objects
dict_items, dict_keys and dict_values respectively. These objects are iterators, and
hence we can run a for loop over them.
Example

Running a simple for loop over the dictionary object traverses the keys used in it. Example

The dict_items object is a list of key-value tuples over which a for loop can be run as
Open Compiler
follows −

numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"} Open Compiler


for x in numbers:
print (x)
numbers = {10:"Ten", 20:"Twenty", 30:"Thirty",40:"Forty"}
for x in [Link]():
On executing, this code will produce the following output − print (x)

10
It will produce the following output −
20
30
(10, 'Ten')
40
(20, 'Twenty')
(30, 'Thirty')
Once we are able to get the key, its associated value can be easily accessed either by (40, 'Forty')
using square brackets operator or with the get() method.
Using else Statement with For Loop
Python supports to have an else statement associated with a loop statement. TOP TUTORIALS
However, the else statement is executed when the loop has exhausted iterating the
Python Tutorial
list.
Java Tutorial

Example C++ Tutorial

C Programming Tutorial
The following example illustrates the combination of an else statement with a for
C# Tutorial
statement that searches for prime numbers from 10 to 20.
PHP Tutorial
R Tutorial
Open Compiler
HTML Tutorial

CSS Tutorial
#For loop to iterate between 10 to 20
JavaScript Tutorial
for num in range(10, 20):
#For loop to iterate on the factors SQL Tutorial
for i in range(2,num):
#If statement to determine the first factor TRENDING TECHNOLOGIES
if num%i == 0:
Cloud Computing Tutorial
#To calculate the second factor
Amazon Web Services Tutorial
j=num/i
Microsoft Azure Tutorial
print ("%d equals %d * %d" % (num,i,j))
#To move to the next number Git Tutorial
break Ethical Hacking Tutorial
else: Docker Tutorial
print (num, "is a prime number")
Kubernetes Tutorial
break
DSA Tutorial
Spring Boot Tutorial
When the above code is executed, it produces the following result − SDLC Tutorial

Unix Tutorial
10 equals 2 * 5
11 is a prime number
12 equals 2 * 6
13 is a prime number
14 equals 2 * 7
15 equals 3 * 5
16 equals 2 * 8
17 is a prime number
18 equals 2 * 9
19 is a prime number
CERTIFICATIONS

Business Analytics Certification

Java & Spring Boot Advanced Certification Tutorials Point is a leading Ed Tech company striving to provide the best learning material
Data Science Advanced Certification on technical and non-technical subjects.

Cloud Computing And DevOps


© Copyright 2025. All Rights Reserved.
Advanced Certification In Business Analytics
Artificial Intelligence And Machine Learning
DevOps Certification

Game Development Certification

Front-End Developer Certification


AWS Certification Training

Python Programming Certification

COMPILERS & EDITORS

Online Java Compiler


Online Python Compiler

Online Go Compiler
Online C Compiler

Online C++ Compiler


Online C# Compiler

Online PHP Compiler


Online MATLAB Compiler
Online Bash Compiler

Online SQL Compiler


Online Html Editor

ABOUT US | OUR TEAM | CAREERS | JOBS | CONTACT US | TERMS OF USE |

PRIVACY POLICY | REFUND POLICY | COOKIES POLICY | FAQ'S

You might also like