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
2. The while Loop: Repeating Until a Condition Changes
The while loop executes a block of code repeatedly as long as a specified condition remains True. It's ideal when you don't know in advance how many times you need to loop, but rather want to continue until some criteria are met.
Syntax:
while condition:
# Code block to execute as long as condition is True
# (MUST be indented)
# Important: Make sure the condition eventually becomes False
-
The `condition` is evaluated at the beginning of each loop iteration. If it's `True`, the block executes. If it's `False`, the loop terminates.
-
Crucially: The code inside the `while` loop must modify some variable involved in the condition, otherwise, you'll create an infinite loop!
Example: Simple Counter
count = 0
print("Counting with while loop:")
while count < 3:
print(f"Count is: {count}")
count += 1 # Increment count, so it eventually becomes 3
print("Loop finished.")
Counting with while loop:
Count is: 0
Count is: 1
Count is: 2
Loop finished.
Example: User Input Loop (UdaanPath Password)
correct_password = "UdaanPass123"
user_tries = 0
print("Please enter the secret UdaanPath password.")
while user_tries < 3:
entered_password = input("Password: ")
if entered_password == correct_password:
print("Access granted! Welcome, UdaanPath Learner.")
break # Exit the loop immediately upon success
else:
user_tries += 1
print(f"Incorrect password. You have {3 - user_tries} tries left.")
if user_tries == 3 and entered_password != correct_password:
print("Too many incorrect attempts. Access denied.")
Please enter the secret UdaanPath password.
Password: wrong
Incorrect password. You have 2 tries left.
Password: again
Incorrect password. You have 1 tries left.
Password: fail
Incorrect password. You have 0 tries left.
Too many incorrect attempts. Access denied.
Password: UdaanPass123
Access granted! Welcome, UdaanPath Learner.
Interview Tip: Differentiate when to use `for` vs. `while`. `for` is usually for iterating over a known sequence or count; `while` is for repeating based on a condition that may change unpredictably (like user input or data availability).
3. Loop Control Statements: break and continue
Sometimes, you need more granular control over loop execution. Python provides two keywords for this:
-
break: Immediately terminates the current loop (the innermost one it's in). Program execution resumes at the statement immediately following the loop.
-
continue: Skips the rest of the code inside the current loop iteration and moves to the next iteration (or re-evaluates the `while` condition).
Example: Using break (Searching for a specific item)
fruits = ["apple", "banana", "cherry", "orange", "grape"]
search_fruit = "cherry"
print(f"Searching for '{search_fruit}':")
for fruit in fruits:
if fruit == search_fruit:
print(f"Found {search_fruit}!")
break # Exit the loop once found
print(f"Still looking... current fruit: {fruit}")
print("Search complete.")
Searching for 'cherry':
Still looking... current fruit: apple
Still looking... current fruit: banana
Found cherry!
Search complete.
Example: Using continue (Skipping even numbers)
print("Printing only odd numbers from 1 to 5:")
for number in range(1, 6): # numbers 1, 2, 3, 4, 5
if number % 2 == 0: # If number is even
continue # Skip the print statement for even numbers
print(f"Odd number: {number}")
Printing only odd numbers from 1 to 5:
Odd number: 1
Odd number: 3
Odd number: 5
4. Nested Loops: Loops Within Loops
Just like `if` statements, loops can be nested, meaning one loop can be placed inside another. The inner loop completes all its iterations for each single iteration of the outer loop.
Example: Multiplication Table (UdaanPath Math Challenge)
print("UdaanPath Multiplication Table (1-3):")
for i in range(1, 4): # Outer loop for rows (1, 2, 3)
for j in range(1, 4): # Inner loop for columns (1, 2, 3)
product = i * j
print(f"{i} * {j} = {product}\t", end="") # \t for tab, end="" to stay on same line
print() # Newline after each row (outer loop iteration)
UdaanPath Multiplication Table (1-3):
1 * 1 = 1 1 * 2 = 2 1 * 3 = 3
2 * 1 = 2 2 * 2 = 4 2 * 3 = 6
3 * 1 = 3 3 * 2 = 6 3 * 3 = 9