Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • šŸ“ Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • šŸ“ Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • šŸ“ Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • šŸ“ Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • šŸ“ While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • šŸ“ For Each Assignments
    • šŸ“ All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • šŸ“ Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • šŸ“ Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • šŸ“ Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • šŸ“ Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • šŸ“ Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • šŸ“ Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • šŸ“ Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • šŸ“ Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • šŸ“ Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • šŸ“ Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • šŸ“ Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • šŸ“ Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • šŸ“ Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • šŸ“ Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • šŸ“ Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • šŸ“ Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • šŸ“ Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • šŸ“ Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • šŸ“ Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

šŸ”„ Python Loops: Complete Introduction

Python Loops Introduction - Complete Guide

Loops let you repeat code efficiently — they're the workhorses of programming.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
šŸ“‘ On this page:
  • What are Loops?
  • Why Use Loops?
  • The while Loop
  • The for Loop
  • Nested Loops
  • Loop Control Statements
  • For vs While - When to Use
  • Real-World Examples
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
šŸ“š What You'll Learn Here
  • What loops are — understanding repetition in programming
  • The while loop — repeating code based on a condition
  • The for loop — iterating over sequences
  • Nested loops — loops inside loops
  • Loop control — break, continue, and else
  • For vs While — when to use each loop type
  • Real-world examples — applying loops in practice
  • Hands-on practice with the interactive editor

What are Loops?

A loop is a programming construct that repeats a block of code multiple times. Instead of writing the same code over and over, you write it once and let the loop handle the repetition.

šŸ’” Key insight: Loops are the heart of automation. They let you perform repetitive tasks efficiently and are essential for processing large amounts of data.

Think of loops like a washing machine cycle. You load the clothes, set the cycle, and the machine repeats the washing, rinsing, and spinning steps automatically. Similarly, in programming, loops automate repetitive tasks, saving you time and effort.

Why Use Loops?

Imagine you need to print "Hello" 100 times. Without loops, you'd have to write 100 print statements. With a loop, you write just one and let the loop repeat it. Here's why loops are essential:

  • Efficiency: Write less code, do more work
  • Automation: Automate repetitive tasks
  • Data Processing: Process lists, arrays, and collections
  • Algorithm Implementation: Many algorithms rely on loops
  • User Interaction: Keep programs running until user decides to exit
# Without loop (bad)
print("Hello")
print("Hello")
print("Hello")
# ... 97 more times!

# With loop (good)
for i in range(100):
    print("Hello")

1. The while Loop

The while loop repeats a block of code as long as a condition is True. It's like saying, "While this condition is true, keep doing this."

# Syntax
while condition:
    # Code to repeat

# Example
count = 1
while count <= 5:
    print(count)
    count += 1

# Output:
# 1
# 2
# 3
# 4
# 5

šŸ“– How it works: The condition is checked before each iteration. If True, the code block executes. If False, the loop ends. This is called a "pre-test" loop because the condition is tested before the code runs.

šŸ’” Real-World Use: User Validation

# Keep asking until user enters a valid number
valid = False
while not valid:
    try:
        num = int(input("Enter a number: "))
        valid = True
        print(f"You entered: {num}")
    except ValueError:
        print("Invalid input! Try again.")

2. The for Loop

The for loop iterates over a sequence (like a list, tuple, string, or range). It's perfect for when you know exactly how many times you want to repeat something.

# Syntax
for item in sequence:
    # Code to repeat

# Example 1: Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

# Example 2: Using range()
for i in range(1, 6):
    print(i)

# Output:
# apple
# banana
# cherry
# 1
# 2
# 3
# 4
# 5

šŸ“– How it works: The for loop takes each item from the sequence one by one, executes the code block, and moves to the next item. It automatically stops when there are no more items.

šŸ’” Real-World Use: Shopping Cart Total

# Calculate total price of items in cart
cart = [250, 300, 150, 100]
total = 0
for price in cart:
    total += price
print(f"Total: ₹{total}")

# Output: Total: ₹800

3. Nested Loops

A nested loop is a loop inside another loop. The inner loop runs completely for each iteration of the outer loop. This is useful for working with multi-dimensional data or creating patterns.

# Nested loops for multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(f"{i} x {j} = {i * j}")
    print("-" * 10)

# Output:
# 1 x 1 = 1
# 1 x 2 = 2
# 1 x 3 = 3
# ----------
# 2 x 1 = 2
# 2 x 2 = 4
# 2 x 3 = 6
# ----------
# 3 x 1 = 3
# 3 x 2 = 6
# 3 x 3 = 9
# ----------

4. Loop Control Statements

Python provides three statements to control the flow of loops:

šŸ›‘ break

Exits the loop immediately

ā­ļø continue

Skips the rest of the current iteration

šŸ“Œ else

Runs when the loop completes normally

# break
for i in range(1, 10):
    if i == 5:
        break
    print(i)
# Output: 1 2 3 4

# continue
for i in range(1, 6):
    if i == 3:
        continue
    print(i)
# Output: 1 2 4 5

# else
for i in range(1, 4):
    print(i)
else:
    print("Loop completed!")
# Output: 1 2 3 Loop completed!

5. For vs While - When to Use

Feature for Loop while Loop
Best For Iterating over sequences Repeating until a condition changes
Loop Count Known in advance May be unknown
Risk Lower risk of infinite loops Higher risk of infinite loops
Example Processing a list User input validation

Try It Yourself!

Experiment with loops directly in your browser. Modify the code and see the results in real time.

Loading Pyodide... 0%
Python Code Editor
========================================
LOOPS INTRODUCTION
========================================

1. WHILE LOOP
1 2 3 4 5

2. FOR LOOP
apple banana cherry

3. FOR LOOP WITH RANGE
1 2 3 4 5

4. BREAK
1 2 3 4

5. CONTINUE
1 2 4 5

āœ… Explore different loop types!
šŸ†

šŸŽ‰ You've Learned Python Loops!

You understand while loops, for loops, nested loops, and loop control statements. These are essential for writing efficient Python code!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about Python loops:

1. Which loop is best when you know exactly how many times to repeat?
2. What does the break statement do in a loop?
3. A loop inside another loop is called:
4. When does the else block run in a loop?
5. Which loop has a higher risk of infinite execution?

Frequently Asked Questions

šŸ¤” What is an infinite loop and how do I avoid it? ā–¼

An infinite loop is a loop that never ends because its condition never becomes false. To avoid it, ensure your loop condition changes inside the loop. For while loops, update the variable being tested. For for loops, use a finite sequence or range.

šŸ”§ Can I use break and continue together? ā–¼

Yes! break and continue can be used together in the same loop. continue skips the rest of the current iteration and moves to the next one. break exits the loop completely.

šŸ“ What is the difference between range() in Python 2 and 3? ā–¼

In Python 2, range() returns a list, while xrange() returns an iterator. In Python 3, range() returns an iterator (like Python 2's xrange), which is more memory efficient for large sequences.

šŸ“Š Can I loop through a dictionary in Python? ā–¼

Yes! You can loop through dictionary keys using for key in dict:, values using for value in dict.values():, or both using for key, value in dict.items():.

⚔ Is it better to use for or while for performance? ā–¼

In most cases, for loops are faster and more readable because they handle iteration automatically. while loops are slower because they check the condition each time. Use for when you can, and while when you need more control.

šŸŽÆ Can I use else with a while loop? ā–¼

Yes! The else block in a while loop runs when the condition becomes false normally (not when broken). This is useful for checking if a loop was completed or interrupted.

šŸ“š Where to Go From Here

Now that you understand loops in Python, here are the next topics to explore in detail:

šŸ”„ The while Loop

Deep dive into the while loop with advanced examples.

Learn More →

šŸ”„ The for Loop

Master the for loop with real-world examples.

Learn More →

šŸ“ Loops Assignments

Practice what you've learned with real coding challenges.

Practice →
šŸ“– Interview & FAQ Resources
  • Python Syntax & Variables Interview Questions
  • SQL - Displaying Data from Multiple Tables FAQ
  • SQL Window Functions & Analytic Functions FAQ
  • Python Data Types Interview Questions
  • Python Tuples and Sets Interview Questions
  • Java Basic Input/Output Interview Questions
  • Java Advanced Threads and Concurrency Interview Questions
Previous: Conditional Assignments Next: while Loop →