4.2 Loop Control: while loop, for loop (BT101CO)
Loop control allows you to execute a block of code repeatedly. This is essential for tasks like processing items in a list, performing repetitive calculations, or running a program until a specific condition changes.
1. The while Loop
The while loop is condition-based. It repeats as long as a certain boolean condition remains True. It is best used when you don't know exactly how many times you need to repeat the task.
# Syntax:
while condition:
# code to repeat
# update condition
Solved Example (Counting):
count = 1
while count <= 5:
print("Iteration:", count)
count += 1 # Incrementing the counter
graph TD
A[Start] --> B{Condition True?}
B -- Yes --> C[Execute Code Block]
C --> D[Update Condition]
D --> B
B -- No --> E[End]
2. The for Loop
The for loop is collection-based. It is used to iterate over a sequence (like a list, string, or range). It is best used when you know the number of iterations in advance.
# Syntax:
for variable in sequence:
# code to repeat
Solved Example (String Iteration):
for char in "PYTHON":
print(char, end="-")
# Output: P-Y-T-H-O-N-
3. The range() Function
The for loop is frequently used with the range() function to generate a sequence of numbers.
range(5)→ 0, 1, 2, 3, 4range(1, 6)→ 1, 2, 3, 4, 5range(1, 10, 2)→ 1, 3, 5, 7, 9 (starts at 1, ends before 10, steps by 2)
Solved Example (Sum of first N numbers):
n = 5
total = 0
for i in range(1, n + 1):
total += i
print(f"The sum of first {n} numbers is {total}")
# Output: The sum of first 5 numbers is 15
4. Loop Control Statements
Sometimes you need to change the behavior of a loop while it is running. Python provides three keywords for this:
break: Exits the loop immediately, regardless of the condition.continue: Skips the rest of the current iteration and jumps to the next one.pass: A "do nothing" placeholder used when a statement is syntactically required but you don't want any command to execute.
Example of break and continue:
for num in range(1, 10):
if num == 5:
break # Stops the loop entirely when num is 5
if num % 2 == 0:
continue # Skips printing even numbers
print(num, end=" ")
# Output: 1 3
5. Nested Loops & Pattern Solving
You can place a loop inside another loop. This is commonly used for working with multi-dimensional data or creating patterns.
Example A: Multiplication Table
for i in range(1, 3): # Outer loop (rows)
for j in range(1, 4): # Inner loop (columns)
print(f"{i}*{j}={i*j}", end="\t")
print() # New line after inner loop finishes
Example B: Star Patterns (Ladders)
for i in range(1, 6):
for j in range(1, i + 1):
print("*", end=" ")
print()
* * * * * * * * * * * * * * *
for i in range(5, 0, -1):
for j in range(1, i + 1):
print("*", end=" ")
print()
* * * * * * * * * * * * * * *
for i in range(1, 6):
for j in range(1, i + 1):
print(j, end=" ")
print()
1 1 2 1 2 3 1 2 3 4 1 2 3 4 5
n = 5
for i in range(1, n + 1):
# Print leading spaces
for j in range(n - i):
print(" ", end=" ")
# Print stars
for k in range(i):
print("*", end=" ")
print()
*
* *
* * *
* * * *
* * * * *
n = 5
for i in range(1, n + 1):
print(" " * (n - i) + "*" * (2 * i - 1))
*
***
*****
*******
*********
n = 5
for i in range(n):
for j in range(n):
if i == 0 or i == n-1 or j == 0 or j == n-1:
print("*", end=" ")
else:
print(" ", end=" ")
print()
* * * * * * * * * * * * * * * *
num = 1
for i in range(1, 6):
for j in range(1, i + 1):
print(num, end=" ")
num += 1
print()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15