Control Flow: Loops in Python
Loops allow you to execute a block of code multiple times, depending on a condition. Python provides two primary types of loops:
forloop: Used for iterating over a sequence (such as a list, tuple, or string).whileloop: Continues executing as long as a given condition isTrue.
Additionally, Python has loop control statements like break, continue, and pass, which control the flow of loops.
Subtopic 1: For Loops
The for loop is typically used when you have a sequence (such as a list, tuple, dictionary, set, or string) to iterate over.
Syntax
for item in sequence:
# Code block executed for each item in the sequence
Example
# Example of for loop with a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Explanation:
- The
forloop iterates over each element in thefruitslist and prints it.
You can also use the range() function to generate a sequence of numbers for iteration.
# Example using range()
for i in range(5): # This will print numbers from 0 to 4
print(i)
Output:
0
1
2
3
4
Subtopic 2: While Loops
The while loop executes a block of code as long as the given condition is True. If the condition is initially False, the block of code will not be executed.
Syntax
while condition:
# Code block executed as long as condition is True
Example
# Example of while loop
count = 0
while count < 5:
print(count)
count += 1 # Increment the counter to avoid infinite loop
Output:
0
1
2
3
4
Explanation:
- The
whileloop checks if thecountis less than 5. IfTrue, it prints the value ofcountand increments it. The loop stops whencountreaches 5.
Subtopic 3: Nested Loops
You can place one loop inside another. This is useful when working with multi-dimensional data structures, such as a list of lists.
Syntax
for outer_item in outer_sequence:
for inner_item in inner_sequence:
# Code block executed for each combination of outer_item and inner_item
Example
# Example of nested for loop
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
for row in matrix:
for element in row:
print(element, end=" ")
print() # For newline after each row
Output:
1 2 3
4 5 6
7 8 9
Explanation:
- The outer
forloop iterates over each row of thematrix(which is a list of lists), and the innerforloop iterates over each element of the current row.
Subtopic 4: Loop Control Statements (break, continue, pass)
Control statements help you modify the flow of execution within loops.
break: Exits the loop entirely.continue: Skips the current iteration and moves to the next iteration.pass: A placeholder that does nothing; useful when you have a loop or condition with no code in it.
break Example
# Example of break in a loop
for i in range(10):
if i == 5:
break # Exits the loop when i is 5
print(i)
Output:
0
1
2
3
4
continue Example
# Example of continue in a loop
for i in range(10):
if i % 2 == 0:
continue # Skips even numbers
print(i)
Output:
1
3
5
7
9
pass Example
# Example of pass in a loop
for i in range(3):
if i == 2:
pass # Does nothing when i is 2
print(i)
Output:
0
1
2
Explanation:
break: The loop terminates wheni == 5.continue: The loop skips printing even numbers.pass: The loop does nothing wheni == 2.
Tasks
-
Task 1: Print Even Numbers Using For Loop
- Write a Python program that prints all even numbers between 1 and 20 using a
forloop.
for i in range(1, 21): if i % 2 == 0: print(i) - Write a Python program that prints all even numbers between 1 and 20 using a
-
Task 2: Sum of Numbers in a List Using For Loop
- Write a program that calculates the sum of all numbers in a list using a
forloop.
numbers = [1, 2, 3, 4, 5] total = 0 for num in numbers: total += num print("Sum:", total) - Write a program that calculates the sum of all numbers in a list using a
-
Task 3: Count Down Using While Loop
- Write a program that counts down from 10 to 1 using a
whileloop.
count = 10 while count > 0: print(count) count -= 1 - Write a program that counts down from 10 to 1 using a
-
Task 4: Nested Loop for Multiplication Table
- Write a Python program that generates a multiplication table (from 1 to 5) using a nested
forloop.
for i in range(1, 6): for j in range(1, 6): print(f"{i} * {j} = {i * j}") print() # Print a newline after each row - Write a Python program that generates a multiplication table (from 1 to 5) using a nested
-
Task 5: Skip Odd Numbers Using Continue
- Write a program that prints all numbers from 1 to 10, but skips odd numbers using the
continuestatement.
for i in range(1, 11): if i % 2 != 0: continue print(i) - Write a program that prints all numbers from 1 to 10, but skips odd numbers using the
-
Task 6: Infinite Loop with Break
- Write a program that creates an infinite loop that will print "Hello, World!" until the user enters "stop".
while True: user_input = input("Enter a command (type 'stop' to exit): ") if user_input == 'stop': break print("Hello, World!")