- Get link
- X
- Other Apps
Loops in Python are used to repeat a block of code multiple times. They are essential for automating repetitive tasks, processing data structures, and implementing logic that requires iteration.
Types of Loops in Python
forLoopUsed to iterate over a sequence (like a list, tuple, string, or range).
Syntax:
for item in sequence: # Code to executeExample:
fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)Using
range()withforLoop:range(start, stop, step)generates a sequence of numbers.- Example:
for i in range(1, 6): # 1 to 5 print(i)
whileLoopRepeats a block of code as long as a condition is
True.Syntax:
while condition: # Code to executeExample:
count = 1 while count <= 5: print(count) count += 1
Loop Control Statements
break- Exits the loop prematurely.
- Example:
for i in range(1, 10): if i == 5: break print(i)
continue- Skips the rest of the loop body and goes to the next iteration.
- Example:
for i in range(1, 6): if i == 3: continue print(i)
elsewith Loops- The
elseblock runs when the loop completes normally (nobreak). - Example:
for i in range(1, 4): print(i) else: print("Loop finished")
- The
Nested Loops
- A loop inside another loop.
- Example:
for i in range(1, 4): for j in range(1, 4): print(f"i={i}, j={j}")
Iterating Over Data Structures
List:
numbers = [10, 20, 30] for num in numbers: print(num)String:
for char in "Python": print(char)Dictionary:
person = {"name": "Alice", "age": 25} for key, value in person.items(): print(f"{key}: {value}")Set:
unique_numbers = {1, 2, 3} for num in unique_numbers: print(num)
Common Applications of Loops
Calculating Factorial:
num = 5 factorial = 1 for i in range(1, num + 1): factorial *= i print(f"Factorial of {num} is {factorial}")Summing Numbers in a List:
numbers = [1, 2, 3, 4, 5] total = 0 for num in numbers: total += num print(f"Sum: {total}")Finding Prime Numbers:
for num in range(2, 10): for i in range(2, num): if num % i == 0: break else: print(f"{num} is a prime number")
Best Practices for Using Loops
Avoid Infinite Loops: Ensure
whileloops have a stopping condition.while True: # Infinite loop break # Always include a way to exitUse List Comprehensions Where Possible:
- They are more Pythonic and concise.
- Example:
squares = [x ** 2 for x in range(1, 6)] print(squares)
Optimize Loops for Performance: Minimize operations inside the loop to improve speed.
Conclusion
Loops are a fundamental part of Python programming. They allow automation of repetitive tasks, efficient data processing, and dynamic problem-solving. By mastering loops and their control statements, you can write clean and efficient Python code.
- Get link
- X
- Other Apps
.jpeg)
Perfect
ReplyDelete