Python for Loop
for is the most commonly used loop statement in Python, used to iterate over iterable objects (sequences, dictionaries, sets, etc.).
Python’s for loop is simpler and more powerful than languages like C/C++, requiring no manual management of loop variables and directly iterating over elements.
Word Meaning: for means “for each” or “for every”, used for iterative traversal.
Basic Syntax and Parameters
Section titled “Basic Syntax and Parameters”Syntax Format
Section titled “Syntax Format”Syntax Description
Section titled “Syntax Description”- variable: The element taken from the iterable object in each iteration.
- iterable: Lists, tuples, strings, dictionaries, sets, range, etc.
- Indentation: The loop body must be indented.
else Clause
Section titled “else Clause”- Optional: The for loop can have an else clause.
- Execution Timing: Executed when the loop ends normally (without exiting via break).
Examples
Section titled “Examples”Example 1: Iterating Over a List
Section titled “Example 1: Iterating Over a List”Example
Section titled “Example”Expected Output:
Code Explanation:
- The for loop directly iterates over each element in the list.
- enumerate() provides both index and value simultaneously.
Example 2: Iterating Over Strings and Tuples
Section titled “Example 2: Iterating Over Strings and Tuples”Example
Section titled “Example”Expected Output:
Strings and tuples are also iterable.
Example 3: Iterating Over a Dictionary
Section titled “Example 3: Iterating Over a Dictionary”Example
Section titled “Example”Expected Output:
The items(), keys(), and values() methods of a dictionary can iterate over different parts.
Example 4: for Loop with else
Section titled “Example 4: for Loop with else”Example
Section titled “Example”Expected Output:
The else clause of the for-else structure does not execute when the loop is terminated by break.
Example 5: Nested Loops
Section titled “Example 5: Nested Loops”Example
Section titled “Example”Expected Output:
Nested loops can be used to process multi-dimensional data structures or generate tables.
Python3 Loop Statements