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 Infinite For Loop: Complete Guide

Python Infinite For Loop - Complete Guide

An infinite for loop runs forever until you stop it. Learn how to create and control them in Python.

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:
  • Welcome: What is an Infinite For Loop?
  • Step 1: The Concept of Infinite Loops
  • Step 2: Creating an Infinite For Loop
  • Step 3: Using break to Exit
  • Step 4: Real-World Examples
  • Step 5: Infinite For vs Infinite While
  • Step 6: Common Mistakes
  • Try It Yourself
  • Quick Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
📚 What You'll Learn Here
  • What an infinite for loop is — a loop that never ends
  • How to create one — using iterators and generators
  • How to control it — using break to exit
  • Real-world applications — menu systems, games, and more
  • Differences from infinite while loops — when to use which
  • Common mistakes — and how to avoid them

Welcome: What is an Infinite For Loop?

📖 Think of it this way: Imagine you're at a buffet that never closes. You can keep going back for more food as many times as you want. The only thing that stops you is your own decision to leave. That's exactly what an infinite for loop is — a loop that keeps running until you decide to stop it.

An infinite for loop is a for loop that never ends on its own. Unlike a regular for loop that stops after a fixed number of iterations, an infinite for loop continues forever. But here's the thing — in Python, a traditional for loop with range() has a fixed end. So how do we create an infinite for loop? We use iterators and generators that never run out of items, or we use the while True approach with a for loop inside.

💡 Key insight: The most common way to create an infinite for loop in Python is by using the iter() function with a callable that never stops, or by using a generator that yields values indefinitely.

Step 1: The Concept of Infinite Loops

1

Understanding the Basics

Before we dive into infinite for loops, let's understand what makes a loop infinite.

# A regular for loop has a fixed end
for i in range(5):
    print(i)  # This runs exactly 5 times

# This is NOT infinite — it stops after 5 iterations

# An infinite loop has no end condition
# In Python, we typically use while True for infinite loops
# But we can also create infinite for loops with iterators!

Why would you want an infinite loop?

  • Menu systems — Keep showing the menu until the user chooses to exit
  • Game loops — Keep the game running until the player quits
  • Server programs — Keep listening for requests forever
  • Event listeners — Keep waiting for events

✅ Quick Check: What's the difference between a regular loop and an infinite loop? (Answer: A regular loop stops after a condition is met; an infinite loop never stops on its own)

Step 2: Creating an Infinite For Loop

2

Using iter() with a Callable

The most common way to create an infinite for loop is using iter() with a callable that always returns the same value:

# Method 1: Using iter() with a callable that always returns True
# This creates an infinite sequence of 1s
for i in iter(lambda: 1, None):
    print(i)  # This will print 1 forever
    # You need to use break to stop it!

# Method 2: Using itertools.count() (import itertools first)
import itertools
for i in itertools.count():
    print(i)  # This will print 0, 1, 2, 3, ... forever
    # You need to use break to stop it!

# Method 3: Using a generator that yields values indefinitely
def infinite_generator():
    while True:
        yield 1  # Always yields 1

for i in infinite_generator():
    print(i)  # This will print 1 forever
    # You need to use break to stop it!

Which method should you use?

  • For simple infinite loops — Use iter(lambda: True, None)
  • For counting infinitely — Use itertools.count()
  • For custom behavior — Write your own generator

💡 Pro Tip: In practice, most Python developers use while True for infinite loops. It's cleaner and more readable. But knowing how to create infinite for loops is useful when working with iterators and generators.

✅ Quick Check: What happens if you run for i in iter(lambda: 1, None): print(i) without a break? (Answer: It runs forever!)

Step 3: Using break to Exit

3

Controlling the Loop with break

An infinite loop is useless without a way to exit it. The break statement is your exit strategy:

import itertools

# Example 1: Count up to 10 and stop
count = 0
for i in itertools.count():
    print(i)
    count += 1
    if count == 10:
        break
# Output: 0 1 2 3 4 5 6 7 8 9

# Example 2: Stop when a condition is met
for i in itertools.count():
    if i == 10:
        break
    print(i)
# Output: 0 1 2 3 4 5 6 7 8 9

# Example 3: Using input to stop
for i in iter(lambda: True, None):
    print("Loop is running...")
    choice = input("Type 'exit' to stop: ")
    if choice == "exit":
        break
print("Loop stopped!")

How break works:

  • The break statement immediately exits the loop
  • You can use if statements to check conditions
  • You can also use continue to skip iterations
  • Always have a way to exit an infinite loop!

✅ Quick Check: What keyword do you use to exit an infinite loop? (Answer: break)

Step 4: Real-World Examples

4

Practical Applications

Here are some real-world scenarios where infinite for loops are useful:

💡 Example 1: Menu System

import itertools

# A restaurant menu that keeps showing until you exit
print("=== WELCOME TO THE MENU ===")
for _ in iter(lambda: True, None):
    print("\n1. View Menu")
    print("2. Place Order")
    print("3. Check Bill")
    print("4. Exit")
    
    choice = int(input("Enter your choice: "))
    
    if choice == 4:
        print("Thank you for visiting!")
        break
    elif choice == 1:
        print("Menu: Pizza, Burger, Pasta, Salad")
    elif choice == 2:
        print("Order placed!")
    elif choice == 3:
        print("Your bill is ₹500")
    else:
        print("Invalid choice!")

💡 Example 2: Digital Clock

import itertools
import time

# A simple digital clock that updates every second
print("=== DIGITAL CLOCK ===")
for _ in iter(lambda: True, None):
    # Get the current time
    current_time = time.strftime("%H:%M:%S")
    print(f"\rCurrent Time: {current_time}", end="")
    time.sleep(1)
    # Press Ctrl+C to stop this!

💡 Example 3: Guessing Game

import itertools
import random

# A number guessing game that keeps running
target = random.randint(1, 100)
print("=== GUESS THE NUMBER ===")
print("I'm thinking of a number between 1 and 100")

for _ in iter(lambda: True, None):
    try:
        guess = int(input("Your guess: "))
    except ValueError:
        print("Please enter a valid number!")
        continue
    
    if guess == target:
        print(f"Correct! The number was {target}")
        break
    elif guess < target:
        print("Too low! Try again.")
    else:
        print("Too high! Try again.")

✅ Quick Check: Why do we use infinite loops in menu systems? (Answer: Because the menu should keep showing until the user chooses to exit)

Step 5: Infinite For vs Infinite While

5

Which One Should You Use?

Both infinite for and infinite while loops can do the same thing. Here's how to choose:

✅ Infinite For Loop

  • You need to iterate over an infinite sequence
  • You're working with generators
  • You need a counter that goes on forever
  • Example: for i in itertools.count():

✅ Infinite While Loop

  • You need a simple infinite loop
  • You don't need an infinite counter
  • You want cleaner, more readable code
  • Example: while True:
# Infinite For Loop
import itertools
for i in itertools.count():
    if i == 10:
        break
    print(i)

# Infinite While Loop
i = 0
while True:
    if i == 10:
        break
    print(i)
    i += 1

# Both produce the same output: 0 1 2 3 4 5 6 7 8 9

💡 Recommendation: In most cases, use while True. It's simpler, more readable, and what most Python developers expect. Use infinite for loops only when you specifically need an infinite iterator.

✅ Quick Check: Which is more commonly used for infinite loops in Python: infinite for or infinite while? (Answer: Infinite while — while True)

Step 6: Common Mistakes to Avoid

6

Watch Out For These!

❌ Mistake 1: Forgetting the break Statement

This creates a loop that never ends:

import itertools

# WRONG (no break)
for i in itertools.count():
    print(i)  # This runs forever!

# CORRECT (with break)
for i in itertools.count():
    if i == 10:
        break
    print(i)

❌ Mistake 2: Infinite Loop Without Purpose

Always have a clear reason for an infinite loop:

# WRONG (pointless infinite loop)
import itertools
for i in itertools.count():
    print(i)  # Why? This just wastes CPU!

# CORRECT (purposeful infinite loop)
import itertools
for i in itertools.count():
    print(f"Iteration {i}")
    if i >= 100:
        break  # Stops after 100 iterations

❌ Mistake 3: Not Using Break on User Input

If you're using user input to control the loop, always provide an exit option:

# WRONG (no exit option)
for _ in iter(lambda: True, None):
    name = input("Enter name: ")
    print(f"Hello, {name}")

# CORRECT (with exit option)
for _ in iter(lambda: True, None):
    name = input("Enter name (or 'exit' to stop): ")
    if name == "exit":
        break
    print(f"Hello, {name}")

✅ Quick Check: What's the most common mistake with infinite loops? (Answer: Forgetting the break statement)

Try It Yourself!

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

Loading Pyodide... 0%
Python Code Editor
========================================
INFINITE FOR LOOP - PRACTICE
========================================

1. COUNT UP TO 10
0 1 2 3 4 5 6 7 8 9

2. COUNT WITH STEP (2)
2 4 6 8 10

3. MENU SYSTEM (Simulated)
Exiting...

✅ Explore infinite loops!
🏆

🎉 You've Mastered Infinite For Loops!

You understand infinite for loops, how to create them, and how to control them with break statements. This is a powerful tool for interactive programs!

Quick Quiz – Test Your Knowledge

Let's see what you've learned about infinite for loops:

1. What is the most common way to create an infinite loop in Python?
2. How do you exit an infinite loop?
3. Which module provides a function for infinite counting?
4. What happens if you run an infinite loop without a break?
5. Which is better for a simple infinite loop?

Frequently Asked Questions

🤔 Can a for loop be infinite without using break? ▼

Yes! If you use a generator or iterator that never runs out of items, a for loop will run forever. For example, for i in iter(lambda: True, None): will run infinitely because the iterator always yields True.

🔧 Is while True better than infinite for? ▼

Yes, while True is the preferred way to create infinite loops in Python. It's cleaner, more readable, and what most Python developers expect. Infinite for loops are useful in specific scenarios with iterators and generators.

📐 What happens if you accidentally create an infinite loop? ▼

Your program will stop responding and may crash your computer if it consumes too much CPU. You can stop it by pressing Ctrl+C (or Cmd+C on Mac) to interrupt the program. Always test infinite loops carefully!

📊 When should I use an infinite loop? ▼

Use infinite loops when you need a program to keep running until a specific event occurs. Common examples include: menu systems, game loops, server programs, and event listeners. Always provide a way to exit!

⚡ Can I use break in a nested infinite loop? ▼

Yes! The break statement only exits the innermost loop. To break out of multiple nested loops, you need to use a flag variable or wrap your loops in a function and use return.

🎯 What's the difference between break and continue? ▼

break exits the loop completely. continue skips the rest of the current iteration and moves to the next one. In an infinite loop, continue keeps the loop running but skips the current iteration.

📚 Where to Go From Here

Now that you've mastered infinite for loops, here are the next topics to explore:

⚡ Break, Continue, Else

Learn how to control loop execution with break and continue.

Learn More →

🔄 For vs While

Understand the differences between for and while loops.

Learn More →

♾️ Infinite While Loop

Learn about infinite while loops and how they compare.

Learn More →
📖 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
Previous: Infinite While Loop Next: Break, Continue, Else →