9.Loops in Python: for, while, break, continue
Loops are fundamental in programming, allowing you to execute a block of code repeatedly. In Python, loops help automate repetitive tasks efficiently. The two primary loop types are for loops and while loops. Additionally, Python provides control statements like break and continue to manage loop execution.
For Loop
A for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. It executes the block of code for each item in the sequence.
Syntax:
for variable in sequence:
# code block
Example:
for num in [1, 2, 3, 4, 5]:
print(num)
Use Cases:
A for loop is used to iterate over a sequence (such as a list, tuple, dictionary, set, or string) or other iterable objects. It executes the block of code for each item in the sequence.
– Iterating through lists or strings
– Performing actions on each element
– Generating sequences
While Loop
A while loop executes a block of code as long as a specified condition is true. It is useful when the number of iterations is not known beforehand.
Syntax:
while condition:
# code block
Example
count = 1
while count <= 5:
print(count)
count += 1
Use Cases:
– Reading data until a condition is met
– Waiting for user input
– Continuous monitoring tasks
Control Statements: break and continue
Python provides break and continue statements to alter the flow of loops.
Terminates the loop immediately and transfers control to the next statement after the loop.
break:
Example:
for num in range(1, 10):
if num == 5:
break
print(num)
Continue:
Skips the current iteration and moves to the next iteration of the loop.
Example:
for num in range(1, 6):
if num == 3:
continue
print(num)
Nested Loops :
You can place one loop inside another. Nested loops are useful for working with multi-dimensional data structures.
Example:
for i in range(1, 4):
for j in range(1, 3):
print(f’i={i}, j={j}’)
Practical Examples
- Summing numbers in a list:
nums = [1, 2, 3, 4]
total = 0
for n in nums:
total += n
print(‘Sum:’, total)
2.Searching for an item:
Items = [‘apple’, ‘banana’, ‘cherry’]
for item in items:
if item == ‘banana’:
print(‘Found banana!’)
break
3.Skipping even numbers:
for num in range(1, 10):
if num % 2 == 0:
continue
print(num)
Conclusion
Loops are powerful tools in Python that help automate repetitive tasks. Understanding for and while loops, along with break and continue statements, is essential for writing efficient programs. Practice these concepts with different examples to master Python looping constructs.