3 2 1 For Loop Explained
Key Concepts
The 3 2 1 For Loop in Python is a fundamental control flow statement used to iterate over a sequence of items. The key concepts include:
- Basic Structure of a For Loop
- Iterating Over Sequences
- Using the
range()
Function
1. Basic Structure of a For Loop
A For Loop allows you to execute a block of code repeatedly for each item in a sequence. The basic structure is:
for variable in sequence: # Code to execute for each item in the sequence
Example:
for i in [1, 2, 3, 4, 5]: print(i)
In this example, the loop iterates over the list [1, 2, 3, 4, 5]
and prints each number.
2. Iterating Over Sequences
For Loops can iterate over various types of sequences, including lists, tuples, strings, and dictionaries.
Example with a list:
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)
Example with a string:
message = "Hello" for char in message: print(char)
Example with a dictionary:
person = {"name": "Alice", "age": 25, "city": "New York"} for key in person: print(key, ":", person[key])
3. Using the range()
Function
The range()
function generates a sequence of numbers, which can be used in a For Loop to iterate a specific number of times.
Example:
for i in range(5): print("Iteration:", i)
In this example, the loop iterates 5 times, with i
taking values from 0 to 4.
Example with a start and stop value:
for i in range(2, 7): print("Number:", i)
In this example, the loop iterates from 2 to 6.
Example with a step value:
for i in range(0, 10, 2): print("Even number:", i)
In this example, the loop iterates from 0 to 8, with a step of 2, printing even numbers.
Putting It All Together
By understanding the basic structure, iterating over sequences, and using the range()
function, you can effectively use For Loops in Python to automate repetitive tasks and process data efficiently.
Example:
numbers = [1, 2, 3, 4, 5] for number in numbers: if number % 2 == 0: print(number, "is even") else: print(number, "is odd")
In this example, the loop iterates over the list of numbers and prints whether each number is even or odd.