for
Loops - Repeating Actionsfor
loops repeat actions for each item in a sequence like lists or strings. Use conditionals to control behavior, and continue/break to skip or exit early.
In this lesson, you'll learn:
for
loops with lists and stringscontinue
to skip itemsbreak
to exit loopsUse for item in list:
to process each item. The loop variable (item) takes on each value in the list sequentially. This syntax works with any iterable, including lists, strings, and ranges, making it extremely versatile for data processing.
numbers = [1, 2, 3]
for num in numbers:
print(num)
Print each fruit in the list.
Strings are sequences, so you can loop through each character. The loop variable will contain one character at a time, allowing you to process text character by character. This is useful for text analysis, validation, or transformation operations.
text = "hello"
for char in text:
print(char)
Print each character in the word.
Add if/elif/else inside loops for conditional actions. The conditional statements are evaluated for each item in the loop, allowing you to perform different operations based on the current item's properties. This creates powerful filtering and processing capabilities.
numbers = [1, 2, 3, 4]
for num in numbers:
if num % 2 == 0:
print(num, "even")
else:
print(num, "odd")
Print "long" if word length > 3, else "short".
continue
skips to the next iteration of the loop. When encountered, it immediately jumps to the next item without executing any remaining code in the current iteration. This is useful for filtering out unwanted items or skipping processing for certain conditions.
numbers = [1, 2, 3, 4]
for num in numbers:
if num == 2:
continue
print(num)
Skip printing "banana".
break
exits the loop early, stopping all further iterations. This is useful when you've found what you're looking for or when a certain condition makes further processing unnecessary. It provides a way to terminate loops prematurely based on runtime conditions.
numbers = [1, 2, 3, 4]
for num in numbers:
if num == 3:
break
print(num)
Stop at "cherry".
Combine loops, conditionals, continue, and break. This example shows how these control structures work together to create sophisticated processing logic that can handle complex data filtering and early termination scenarios.
words = ["cat", "dog", "elephant", "bird"]
for word in words:
if len(word) < 4:
continue
if word == "elephant":
break
print(word)
Loop through numbers, skip evens, break at 7, print odds.
You've learned for loops with lists/strings, conditionals, continue, and break.
Next Steps: Apply loops to more complex data processing!