A `for` loop is used to iterate over items of a sequence (like a list, tuple, or string). Example:
fruits = ['apple', 'banana', 'cherry'] for fruit in fruits: print(fruit) Output: apple banana cherry
A `while` loop repeatedly executes a block of code as long as a condition is true. Example:
i = 0 while i < 5: print(i) i += 1 Output: 0 1 2 3 4
The `break` statement exits the loop immediately. Example:
for i in range(10): if i == 5: break print(i) Output: 0 1 2 3 4
The `continue` statement skips the current iteration and moves to the next one. Example:
for i in range(5): if i == 3: continue print(i) Output: 0 1 2 4
Use `enumerate()` to get both index and value. Example:
for index, value in enumerate(['a', 'b', 'c']): print(index, value) Output: 0 a 1 b 2 c
Use nested loops. Example:
for sublist in [[1, 2], [3, 4]]: for item in sublist: print(item) Output: 1 2 3 4
You can use `for` loops to access each dictionary and its values. Example:
data = [{'name': 'Alice'}, {'name': 'Bob'}] for entry in data: print(entry['name']) Output: Alice Bob
`range()` generates a sequence of numbers. Example:
for i in range(3): print(i) Output: 0 1 2
Use a loop to compare each item. Example:
my_list = [10, 20, 4, 45, 99] max_value = my_list[0] for num in my_list: if num > max_value: max_value = num print(max_value) Output: 99
Use nested comprehensions. Example:
lists = [[1, 2], [3, 4]] flattened = [item for sublist in lists for item in sublist] print(flattened) Output: [1, 2, 3, 4]
Use the `items()` method. Example:
my_dict = {'key1': 'value1', 'key2': 'value2'} for key, value in my_dict.items(): print(key, value) Output: key1 value1 key2 value2
`while` loops continue as long as the condition is true. Example:
count = 0 while count < 5: print(count) count += 1 Output: 0 1 2 3 4
Use the `break` statement. Example:
for i in range(10): if i == 5: break print(i) Output: 0 1 2 3 4
Use the `continue` statement. Example:
for i in range(5): if i == 3: continue print(i) Output: 0 1 2 4