For Loop in Python: Iterating Through Sequences
The `for` loop in Python is used to **iterate through sequences** like lists, tuples, strings, and ranges. It helps automate repetitive tasks efficiently.
Why Use `for` Loops?
- Automates repetitive operations.
- Makes code cleaner and more readable.
- Works with different data structures.
Basic Syntax
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Using `range()` in a For Loop
The `range()` function generates numbers for looping.
for num in range(1, 6):
print(num) # Output: 1, 2, 3, 4, 5
Looping Through a String
for letter in "Python":
print(letter)
Conclusion
The `for` loop is a powerful tool for iterating through sequences effortlessly. How do you plan to use it in your projects?
While Loop in Python: Repeating Until a Condition is Met
The `while` loop in Python **executes code repeatedly as long as a condition remains true**. It’s ideal for situations where the number of iterations isn’t known beforehand.
Why Use `while` Loops?
- Runs until a condition is false.
- Useful for dynamic loops (e.g., user input).
- Perfect for event-driven logic.
Basic Syntax
count = 1
while count <= 5:
print(count)
count += 1 # Output: 1, 2, 3, 4, 5
Using a `while` Loop for User Input
password = ""
while password != "secret":
password = input("Enter the password: ")
print("Access granted!")
Conclusion
The `while` loop is great for **handling dynamic conditions**. Where do you think it could be useful in your projects?