27. for loops & range() function
Iterating over sequences, range(start, stop, step), enumerate(), and zip() parallel iteration in Python. In this interactive tutorial, you will explore conceptual principles, memory models, best practices, executable code samples, and common pitfalls to avoid.
1 Overview & Core Concepts
Iterating over sequences, range(start, stop, step), enumerate(), and zip() parallel iteration in Python. Python offers clean syntax and powerful built-in abstractions that streamline software development across web, machine learning, and automation workflows.
2 Executable Code Example
Python 3
โถ Run in Compiler
# for loop with range()
print("Counting from 1 to 5:")
for i in range(1, 6):
print(f" Step {i}")
# Iterating over collection with enumerate
fruits = ["Apple", "Mango", "Banana"]
for idx, fruit in enumerate(fruits, start=1):
print(f"{idx}. {fruit}")
โ ๏ธ Key Best Practice & Common Pitfalls
Always write clean, PEP 8 compliant code with descriptive variable names and consistent 4-space indentation. Test your code in the online sandbox above before deploying to production.
๐ป Try It Yourself โ Practice Challenge
Modify and test this interactive coding challenge in Our Compiler:
Python 3
โถ Run in Compiler
# Sum of all even numbers from 1 to 20
total = sum([x for x in range(1, 21) if x % 2 == 0])
print(f"Sum of evens (1-20): {total}")
โ Frequently Asked Questions (FAQ)
Q: What is the main objective of 27. for loops & range() function?
Iterating over sequences, range(start, stop, step), enumerate(), and zip() parallel iteration in Python.
Q: How do I test this code without installing Python?
Click the green 'โถ Run in Compiler' button on any code block to execute directly in Our Compiler's cloud sandbox.