Table of contents

Loops (for, while) : A Comprehensive Guide

Loops are fundamental constructs in programming that allow you to execute a block of code repeatedly. Python provides two primary types of loops: for loops and while loops. This comprehensive guide will explore these loops, their syntax, usage, and practical examples to help you master loop constructs in Python.

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

for variable in sequence: # code to execute for each item

Example

fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

In this example, the for loop iterates over the list fruits and prints each fruit.

The range() function generates a sequence of numbers, which is commonly used with for loops.

for i in range(5): print(i)

This loop prints numbers from 0 to 4.

Custom Range

You can specify a start, stop, and step value in the range() function.

for i in range(2, 10, 2): print(i)

This loop prints even numbers from 2 to 8.

You can nest for loops to iterate over multiple sequences.

This nested loop prints every combination of colors and fruits.

The while loop in Python is used to repeatedly execute a block of code as long as a condition is True.

while condition: # code to execute while condition is true

Example

count = 0 while count < 5: print(count) count += 1

In this example, the while loop prints numbers from 0 to 4.

Be cautious with while loops to avoid creating infinite loops, which occur when the condition never becomes False.

while True: print("This will run forever.") break # To prevent an infinite loop

The else block after a while loop executes when the loop condition becomes False.

count = 0 while count < 5: print(count) count += 1 else: print("Loop finished.")

The break statement is used to exit a loop prematurely.

for i in range(10): if i == 5: break print(i)

This loop prints numbers from 0 to 4 and exits when i equals 5.

The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.

for i in range(10): if i % 2 == 0: continue print(i)

This loop prints odd numbers from 1 to 9.

The pass statement does nothing and can be used as a placeholder in loops.

for i in range(5): pass # Do nothing

A program to calculate the sum of the first n natural numbers using a for loop.

n = int(input("Enter a positive integer: ")) sum = 0 for i in range(1, n + 1): sum += i print(f"The sum of the first {n} natural numbers is {sum}.")

A program to calculate the factorial of a number using a while loop.

num = int(input("Enter a positive integer: ")) factorial = 1 while num > 0: factorial *= num num -= 1 print(f"The factorial is {factorial}.")

Write a program to print the multiplication table of a given number using a for loop.

num = int(input("Enter a number: ")) for i in range(1, 11): print(f"{num} x {i} = {num * i}")

Write a program where the user has to guess a secret number between 1 and 100. The program should provide feedback if the guess is too high, too low, or correct. Use a while loop.

import random secret_number = random.randint(1, 100) guess = None while guess != secret_number: guess = int(input("Guess the number (between 1 and 100): ")) if guess < secret_number: print("Too low!") elif guess > secret_number: print("Too high!") else: print("Congratulations! You guessed the number.")

In this guide, we’ve explored Python’s loop constructs (for and while loops), including their syntax, usage, and practical examples. Loops are essential for executing repetitive tasks and iterating over sequences. Practice these concepts with the provided examples and exercises to enhance your understanding and programming skills. In the next section, we will delve into functions, which help you write modular and reusable code. Happy coding!