Bigdata – Knowledge Base

Python Loops – while & for

Loops in Python are used to execute a block of code multiple times until a specified condition is met. Python provides two primary types of loops: for and while. Additionally, Python offers control statements like break, continue, and pass to manage loop execution efficiently.


1. The for Loop #

The for loop in Python is used for iterating over a sequence (list, tuple, dictionary, set, or string).

Syntax: #

Example: Iterating over a list #

Example: Using range() in a for loop #

Example: Iterating over a dictionary #


2. The while Loop #

The while loop executes a block of code as long as a specified condition is True.

Syntax: #

Example: Counting using a while loop #

Example: Using break in a while loop #


3. Loop Control Statements #

a. break Statement #

Terminates the loop when encountered.

b. continue Statement #

Skips the current iteration and moves to the next.

c. pass Statement #

A placeholder used when a statement is syntactically required but no action is needed.


4. Nested Loops #

A loop inside another loop.


5. List Comprehension with Loops #

Python provides a concise way to create lists using loops.


6. Infinite Loops #

Avoid infinite loops by ensuring the loop condition eventually becomes False.


Conclusion #

Python loops provide an efficient way to automate repetitive tasks. By mastering for and while loops, along with control statements, you can write more efficient and readable code.

What are your feelings
Updated on February 16, 2025