TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python For Loop Tutorial
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python For Loop Tutorial

Last updated: Oct 22, 2023 5:20 pm
By Meenakshi Agarwal
Share
8 Min Read
Python for loop, syntax and examples
Python for loop, syntax and examples
SHARE

This tutorial explains Python for loop, and its syntax and provides various examples of iterating over different sequence data types. For loop is the most common control flow statement used by programmers for performing repetitive tasks. The best case to use it is when you know the total no. of iterations required for execution.

Contents
Python For Loop SyntaxFor Loop FlowchartPython For Loop Examples

Python For Loop Definition, Syntax

Python provides a simple and straightforward syntax to use “for loop” in programs. It can help you iterate through different types of objects. Python supports seven sequence data types: standard/Unicode strings, a list, tuples, a byte array, and xrange objects. There are sets and dictionaries as well, but they are just containers for the sequence types.

A for loop in Python requires at least two variables to work. The first is the iterable object such as a list, tuple, or string. And second, is the variable to store the successive values from the sequence in the loop.

Python For Loop Syntax

In Python, you can use the “for” loop in the following manner.

# syntax
for iter in sequence:
    statements(iter)

The “iter” represents the iterating variable. It gets assigned successive values from the input sequence.

The “sequence” may refer to any of the following Python objects such as a list, a tuple, or a string.

For Loop Flowchart

The for loop can include a single line or a block of code with multiple statements. Before executing the code inside the loop, the value from the sequence gets assigned to the iterating variable (“iter”).

Below is the For loop flowchart representation in Python:

Regular Python For Loop Flowchart
Regular Python For Loop Flowchart

Python For Loop Examples

Here is the code using Python for loop to print all characters of a string.

# Program to print the letters of a string using for loop
vowels = "AEIOU"
for iter in vowels:
    print("char:", iter)

""" Output
char: A
char: E
char: I
char: O
char: U
"""

Let’s now widen our logical thinking. Here is a step-by-step procedure to calculate the average of N numbers using a for loop in Python. We’ll use the following steps to compute the avg. of N numbers.

  1. Create a list of integers and populate it with N (=6) values.
  2. Initialize a variable (sum) for storing the summation.
  3. Loop N (=6) number of times to get the value of each integer from the list.
  4. In the loop, add each value with the previous and assign it to a variable named the sum.
  5. Divide the “sum” by N (=6). We used the len() function to determine the size of our list.
  6. The output of the previous step is the average we wanted.
  7. Finally, print both the “sum” and the average.

Below is the Python code for the above program.

# Program to calculate the average of N integers
int_list = [1, 2, 3, 4, 5, 6]
sum = 0
for iter in int_list:
    sum += iter
print("Sum =", sum)
print("Avg =", sum/len(int_list))

Here is the output after executing the above code.

""" Output
Sum = 21
Avg = 3.5
"""

Range() Function with For Loop

Python range() function returns a list or a sequence of numbers at runtime. For example, a statement like range(0, 10) will generate a series of ten integers starting from 0 to 9. The below snippet tries to show that range() returns a list and its elements are available via indexes.

# Check the type of list returned by range() function
print( type(range(0, 10)) )
# <class 'range'>

# Access first element in the range list 
print( range(0, 10)[0] )  # 0

# Access second element
print( range(0, 10)[1] )  # 1

# Access last element
print( range(0, 10)[9] )  # 9

# Caclulayte the size of range list
print( len(range(0, 10)) )  # 10

Let’s now use the range() with a Python “for” loop.

for iter in range(0, 3):
    print("iter: %d" % (iter))

It will yield the following result.

""" Output
iter: 0
iter: 1
iter: 2
"""

By default, the for loop fetches elements from the sequence and assigns them to the iterating variable. But you can also make it return the index by replacing the sequence with a range(len(seq)) expression.

books = ['C', 'C++', 'Java', 'Python']
for index in range(len(books)):
   print('Book (%d):' % index, books[index])

The following lines will get printed.

""" Output
Book (0): C
Book (1): C++
Book (2): Java
Book (3): Python
"""

Else Clause with Python For Loop

Interestingly, Python allows the use of an optional else statement along with the “for” loop.

The code under the else clause executes after the completion of the “for” loop. However, if the loop stops due to a “break” call, then it’ll skip the “else” clause.

Check the below syntax to use the else clause with Python for loop.

# Foe-Else Syntax

for item in seq:
    statement 1
    statement 2
    if <cond>:
        break
else:
    statements

Look at the below For Loop with Else flowchart to understand it more clearly.

Python for loop with else clause flowchart

Below is the sample code that uses a for loop and an else statement.

# Simple Python program to demonstrate the use of else with for loop
birds = ['Belle', 'Coco', 'Juniper', 'Lilly', 'Snow']
ignoreElse = False

for theBird in birds:
    print(theBird )
    if ignoreElse and theBird == 'Snow':
        break
else:
    print("No birds left.")

The above code will print the names of all birds plus the message in the “else” part.

""" Output
Belle
Coco
Juniper
Lilly
Snow
No birds left.
"""

Setting the “ignoreElse” variable to “True” will get the “else” part ignored. And, only the names will get displayed.

Python For Loop Summary

In this tutorial, we explained the concept of Python for Loop with several examples so that you can easily use it in real-time Python programs. However, if you have any questions about this topic, please do write to us.

Also, if you found it useful, then do share it with your colleagues. Also, connect to our social media accounts to receive timely updates.

Best,

TechBeamers

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Selenium WebDriver Waits in Python Explained with Examples Use Selenium WebDriver Waits in Python
Next Article Python while loop Python While Loop Tutorial

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x