1. The for
Loop: Iterating Over Sequences
The for
loop in Python is used for iterating over a sequence (like a string, list, tuple, dictionary, or range) or other iterable objects. It executes a block of code once for each item in the sequence.
Syntax:
for variable in iterable:
# Code block to execute for each item
# (This block MUST be indented)
- `variable`: A temporary variable that takes on the value of the current item in the `iterable` during each iteration.
- `iterable`: Any object that can be iterated over (e.g., strings, lists, `range()` objects).
Example: Looping through a String (UdaanPath letters)
word = "UdaanPath"
print("Letters in 'UdaanPath':")
for char in word:
print(char)
Letters in 'UdaanPath': U d a a n P a t h
The range()
Function: Numerical Iteration
The range()
function is commonly used with `for` loops to generate a sequence of numbers. It's often used when you need to repeat an action a specific number of times.
range(stop)
: Generates numbers from 0 up to (but not including) `stop`.range(start, stop)
: Generates numbers from `start` up to (but not including) `stop`.range(start, stop, step)
: Generates numbers from `start` up to (but not including) `stop`, incrementing by `step` each time.
print("Counting to 5:")
for i in range(5): # 0, 1, 2, 3, 4
print(i + 1) # Print 1 to 5
print("\nNumbers from 5 to 9:")
for num in range(5, 10): # 5, 6, 7, 8, 9
print(num)
print("\nEven numbers from 0 to 10:")
for x in range(0, 11, 2): # 0, 2, 4, 6, 8, 10
print(x)
Counting to 5: 1 2 3 4 5 Numbers from 5 to 9: 5 6 7 8 9 Even numbers from 0 to 10: 0 2 4 6 8 10