Tutorialsteacher

Follow Us

Articles
  • C#
  • C# OOP
  • ASP.NET Core
  • ASP.NET MVC
  • LINQ
  • Inversion of Control (IoC)
  • Web API
  • JavaScript
  • TypeScript
  • jQuery
  • Angular 11
  • Node.js
  • D3.js
  • Sass
  • Python
  • Go lang
  • HTTPS (SSL)
  • Regex
  • SQL
  • SQL Server
  • PostgreSQL
  • MongoDB
  • Python - Get Started
  • What is Python?
  • Where to use Python?
  • Python Version History
  • Install Python
  • Python - Shell/REPL
  • Python IDLE
  • Python Editors
  • Python Syntax
  • Python Keywords
  • Python Variables
  • Python Data Types
  • Number
  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Python Operators
  • Python Conditions - if, elif
  • Python While Loop
  • Python For Loop
  • User Defined Functions
  • Lambda Functions
  • Variable Scope
  • Python Modules
  • Module Attributes
  • Python Packages
  • Python PIP
  • __main__, __name__
  • Python Built-in Modules
  • OS Module
  • Sys Module
  • Math Module
  • Statistics Module
  • Collections Module
  • Random Module
  • Python Generator Function
  • Python List Comprehension
  • Python Recursion
  • Python Built-in Error Types
  • Python Exception Handling
  • Python Assert Statement
  • Define Class in Python
  • Inheritance in Python
  • Python Access Modifiers
  • Python Decorators
  • @property Decorator
  • @classmethod Decorator
  • @staticmethod Decorator
  • Python Dunder Methods
  • CRUD Operations in Python
  • Python Read, Write Files
  • Regex in Python
  • Create GUI using Tkinter
Entity Framework Extensions - Boost EF Core 9
  Bulk Insert
  Bulk Delete
  Bulk Update
  Bulk Merge

Python for Loops

In Python, the for loop is used for iterating over sequence types such as list, tuple, set, range, etc. Unlike other programming language, it cannot be used to execute some code repeatedly.

The body of the for loop is executed for each member element in the sequence. Hence, it doesn't require explicit verification of a boolean expression controlling the loop (as in the while loop).

Syntax:
for x in sequence: statement1 statement2 ... statementN

To start with, a variable x in the for statement refers to the item at the 0 index in the sequence. The block of statements with increased uniform indent after the : symbol will be executed. A variable x now refers to the next item and repeats the body of the loop till the sequence is exhausted.

The following example demonstrates the for loop with the list object.

Example:
nums = [10, 20, 30, 40, 50]

for i in nums:
    print(i)
Try it
Output
10 20 30 40 50

The following demonstrates the for loop with a tuple object.

Example: For Loop with Tuple
nums = (10, 20, 30, 40, 50)
for i in nums:
    print(i)
Try it
Output
10 20 30 40 50

The object of any Python sequence data type can be iterated using the for statement.

Example: For Loop with String
for char in 'Hello':
    print (char)
Try it
Output
H e l l o

The following for loop iterates over the dictionary using the items() method.

Example: For Loop with Dictionary
numNames = { 1:'One', 2: 'Two', 3: 'Three'}

for pair in numNames.items():
    print(pair)
Try it
Output
(1, 'One') (2, 'Two') (3, 'Three')

The key-value paris can be unpacked into two variables in the for loop to get the key and value separately.

Example: For Loop with Dictionary
numNames = { 1:'One', 2: 'Two', 3: 'Three'}

for k,v in numNames.items():
    print("key = ", k , ", value =", v)
Try it
Output
key = 1, value = One key = 2, value = Two key = 3, value = Three

For Loop with the range() Function

The range class is an immutable sequence type. The range() returns the range object that can be used with the for loop.

Example:
for i in range(5):
    print(i)
Try it
Output
0 1 2 3 4

Exit the For Loop

The execution of the for loop can be stop and exit using the break keyword on some condition, as shown below.

Example:
for i in range(1, 5):
    if i > 2 :
        break
    print(i)
Try it
Output
1 2

Continue Next Iteration

Use the continue keyword to skip the current execution and continue on the next iteration using the continue keyword on some condition, as shown below.

Example:
for i in range(1, 5):
    if i > 3:
        continue
    print(i)
Try it
Output
1 2 3

For Loop with Else Block

The else block can follow the for loop, which will be executed when the for loop ends.

Example:
for i in range(2):
    print(i)
else:
     print('End of for loop')
Try it
Output
0 1 End of for loop

Nested for Loop

If a loop (for loop or while loop) contains another loop in its body block, we say that the two loops are nested. If the outer loop is designed to perform m iterations and the inner loop is designed to perform n repetitions, the body block of the inner loop will get executed m X n times.

Example: Nested for loop
for x in range(1,4):
    for y in range(1,3):
        print('x = ', x, ', y = ', y)
Try it
Output
x =  1, y =  1 x =  1, y =  2 x =  2, y =  1 x =  2, y =  2 x =  3, y =  1 x =  3, y =  2
TUTORIALSTEACHER.COM

TutorialsTeacher.com is your authoritative source for comprehensive technologies tutorials, tailored to guide you through mastering various web and other technologies through a step-by-step approach.

Our content helps you to learn technologies easily and quickly for learners of all levels. By accessing this platform, you acknowledge that you have reviewed and consented to abide by our Terms of Use and Privacy Policy, designed to safeguard your experience and privacy rights.

[email protected]

ABOUT USTERMS OF USEPRIVACY POLICY
copywrite-symbol

2024 TutorialsTeacher.com. (v 1.2) All Rights Reserved.