3 2 Loops Explained
Key Concepts
Loops in Python allow you to execute a block of code repeatedly based on a condition. The key concepts include:
forloopwhileloop- Loop control statements:
break,continue, andpass
1. The for Loop
The for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) and execute a block of code for each item in the sequence.
Example:
for i in range(5):
print(i)
Think of the for loop as a way to repeat an action for each item in a collection. In this example, the loop prints numbers from 0 to 4.
2. The while Loop
The while loop is used to execute a block of code as long as a specified condition is true.
Example:
count = 0
while count < 5:
print(count)
count += 1
Think of the while loop as a way to repeat an action until a condition is no longer true. In this example, the loop prints numbers from 0 to 4.
3. Loop Control Statements
Loop control statements allow you to alter the flow of a loop. The key statements are:
break: Exits the loop prematurely.continue: Skips the rest of the loop body and continues with the next iteration.pass: Acts as a placeholder and does nothing.
Example using break:
for i in range(10):
if i == 5:
break
print(i)
Example using continue:
for i in range(10):
if i % 2 == 0:
continue
print(i)
Example using pass:
for i in range(5):
if i == 3:
pass
print(i)
Putting It All Together
By understanding and using for and while loops, along with loop control statements, you can create powerful and flexible iteration structures in your Python programs. These loops allow you to automate repetitive tasks and process data efficiently.
Example:
numbers = [1, 2, 3, 4, 5]
sum = 0
for num in numbers:
if num == 3:
continue
sum += num
print("Sum of numbers (excluding 3):", sum)
This example demonstrates how to sum a list of numbers while skipping a specific value using the continue statement.