Python Loops Tutorial

Introduction

Loops are a fundamental concept in programming that allows you to repeat a block of code multiple times. Python provides two primary loop structures: for loops and while loops. This tutorial covers the basics of using loops in Python, including their syntax and a few simple programs to demonstrate their use.

Table of Contents

  1. For Loops
  2. While Loops
  3. Nested Loops
  4. Loop Control Statements
  5. Practical Examples
  6. Conclusion

1. For Loops

Definition

A for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence.

Syntax

for variable in sequence:
    # Code to execute for each item in the sequence

Example

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

Example with Range

The range() function is often used with for loops to generate a sequence of numbers.

# Iterating over a range of numbers
for i in range(5):
    print(i)

2. While Loops

Definition

A while loop repeatedly executes a block of code as long as a specified condition is true.

Syntax

while condition:
    # Code to execute while the condition is true

Example

# Counting down from 5 to 1
count = 5
while count > 0:
    print(count)
    count -= 1

3. Nested Loops

Definition

Nested loops are loops within loops. The inner loop will be executed one time for each iteration of the outer loop.

Syntax

for variable1 in sequence1:
    for variable2 in sequence2:
        # Code to execute for each combination of items in sequence1 and sequence2

Example

# Printing a multiplication table
for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=' ')
    print()

4. Loop Control Statements

Break

The break statement is used to exit a loop prematurely.

# Breaking out of a loop
for i in range(10):
    if i == 5:
        break
    print(i)

Continue

The continue statement is used to skip the rest of the code inside a loop for the current iteration and continue with the next iteration.

# Skipping an iteration
for i in range(10):
    if i % 2 == 0:
        continue
    print(i)

Pass

The pass statement is a null operation; it is used as a placeholder for future code.

# Using pass as a placeholder
for i in range(5):
    if i == 3:
        pass
    else:
        print(i)

5. Practical Examples

Example 1: Sum of Natural Numbers

# Sum of first 10 natural numbers
sum = 0
for i in range(1, 11):
    sum += i
print("Sum of first 10 natural numbers:", sum)

Example 2: Factorial of a Number

# Factorial of a number using a while loop
number = 5
factorial = 1
while number > 0:
    factorial *= number
    number -= 1
print("Factorial:", factorial)

Example 3: Printing a Pattern

# Printing a pattern using nested loops
rows = 5
for i in range(1, rows + 1):
    for j in range(1, i + 1):
        print("*", end=' ')
    print()

Example 4: Checking for Prime Numbers

# Checking if a number is prime
number = 29
is_prime = True

for i in range(2, number):
    if number % i == 0:
        is_prime = False
        break

if is_prime:
    print(number, "is a prime number")
else:
    print(number, "is not a prime number")

Example 5: Fibonacci Sequence

# Generating the Fibonacci sequence up to n terms
n = 10
a, b = 0, 1
print("Fibonacci sequence:")
for _ in range(n):
    print(a, end=' ')
    a, b = b, a + b

6. Conclusion

Loops are used in programming that allow you to execute a block of code multiple times. Python provides two primary loop structures: for loops and while loops, each suited for different types of tasks. Understanding how to use loops, including nested loops and loop control statements, is essential for writing efficient and effective Python code. This tutorial covered the basics of loops in Python with practical examples to demonstrate their use.

Comments