PY

Python Fundamentals

18 lessons

Progress0%
1. Introduction to Python
1What is Python?2Setting Up Python
2. Variables and Data Types
1Variables in Python2Data Types
3. Control Flow
Conditional StatementsLoops
4. Functions
Function Basics
5. Data Structures
Lists Deep DiveTuples & SetsDictionaries & Comprehensions
6. Advanced Functions
Closures & Higher-Order FunctionsDecorators & Lambda
7. Object-Oriented Python
Classes & InstancesInheritance & Dunder Methods
8. Exception Handling
try / except / finallyCustom Exceptions & Context Managers
9. Modules & File I/O
Modules & PackagesFile I/O & JSON
All Tutorials
PythonControl Flow
Lesson 6 of 18 min
Chapter 3 · Lesson 2

Loops

Loops allow you to execute code multiple times.

for Loop: Iterates over a sequence (list, string, range, etc.)

while Loop: Continues while a condition is True.

Loop Control:

  • break: Exit the loop
  • continue: Skip to next iteration
  • pass: Do nothing (placeholder)

range() Function: Generates a sequence of numbers:

  • range(5): 0, 1, 2, 3, 4
  • range(1, 6): 1, 2, 3, 4, 5
  • range(0, 10, 2): 0, 2, 4, 6, 8

enumerate(): Get both index and value when looping.

zip(): Loop over multiple sequences together.

Code Examples

Python Loopspython
# for loop with range
print("Counting to 5:")
for i in range(1, 6):
    print(i)

# for loop with list
colors = ["red", "green", "blue"]
print("\nColors:")
for color in colors:
    print(color)

# enumerate for index and value
print("\nWith index:")
for index, color in enumerate(colors):
    print(f"{index}: {color}")

# while loop
count = 0
print("\nWhile loop:")
while count < 3:
    print(f"Count: {count}")
    count += 1

# break and continue
print("\nBreak at 3:")
for i in range(1, 6):
    if i == 3:
        break
    print(i)

print("\nSkip even numbers:")
for i in range(1, 6):
    if i % 2 == 0:
        continue
    print(i)

# zip - loop multiple lists
names = ["Alice", "Bob"]
ages = [25, 30]
print("\nZip example:")
for name, age in zip(names, ages):
    print(f"{name} is {age}")

# List comprehension
squares = [x**2 for x in range(1, 6)]
print(f"\nSquares: {squares}")

List comprehensions are a Pythonic way to create lists from loops in a single line.

Quick Quiz

1. What does range(1, 5) produce?

Was this lesson helpful?

PreviousNext