For Loop and While Loop in Python

Abhilash Jose
Abhilash Jose  - Data Science Specialist
3 Min Read

For Loop and While Loop in Python

Loops are a fundamental part of programming that allow you to execute a block of code repeatedly. Python provides two types of loops: the for loop and the while loop. Each has its own use cases and benefits.

For Loop

The for loop is used to iterate over a sequence (like a list, tuple, string, or range) and execute a block of code for each item in the sequence. It’s especially useful when you know in advance how many iterations are required.

Syntax:

Example 1: Iterating Through a List

Output:

Example 2: Using range() in a For Loop

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

Output:

Example 3: For Loop with an Else Block

You can also have an else block with a for loop, which executes when the loop completes its iterations without breaking.

Output:

While Loop

The while loop repeatedly executes a block of code as long as the given condition is True. It’s generally used when the number of iterations is not known beforehand.

Syntax:

Example 1: Simple While Loop

Output:

Example 2: While Loop with Break Condition

The break statement is used to exit the loop when a specific condition is met.

Output:

Example 3: While Loop with an Else Block

Just like the for loop, you can also use an else block with a while loop. The else block runs when the loop condition becomes false, unless the loop is terminated by a break.

Output:

Key Differences Between For and While Loops

  • For Loop: Ideal for iterating over a sequence of known length or when you know the number of iterations beforehand.
  • While Loop: Useful when you want to continue executing a block of code until a certain condition is met, without knowing in advance how many iterations it will take.

Summary

  • For Loops: Use them to iterate over a collection or a specific range of values.
  • While Loops: Use them when the number of iterations isn’t known upfront, and the loop depends on a condition being met.

Share this Article
By Abhilash Jose Data Science Specialist
Follow:
Abhilash Jose is a data science specialist from India. He specializes in data analysis and is well-known for his expertise in areas such as machine learning and statistical modeling. His skills encompass a wide range of techniques, including data mining, predictive modeling, and data visualization.
Leave a comment