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.
Example
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.
This loop prints numbers from 0 to 4.
Custom Range
You can specify a start, stop, and step value in the range() function.
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.
Example
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.
The else block after a while loop executes when the loop condition becomes False.
The break statement is used to exit a loop prematurely.
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.
This loop prints odd numbers from 1 to 9.
The pass statement does nothing and can be used as a placeholder in loops.
A program to calculate the sum of the first n natural numbers using a for loop.
A program to calculate the factorial of a number using a while loop.
Write a program to print the multiplication table of a given number using a for loop.
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.
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!