For Loops
This lesson covers how to use for loops in Python to iterate over sequences and other iterable objects, which is essential for automating repetitive tasks in programming.
A for loop provides a structured way to process every item within a collection, such as a list, tuple, or string. It assigns each item, one by one, to a temporary loop variable, then executes a defined block of code. This process continues until all items in the collection have been processed, making it ideal for tasks that require repeated actions on distinct pieces of data.
Looping Through Sequences: Lists, Tuples, and Strings
Generating Number Sequences with range()
The built-in range() function is commonly used with for loops to generate sequences of numbers. It's particularly useful when you need to repeat an action a specific number of times or iterate through indices. range() can be used in three main ways:
range(stop): Generates numbers from 0 up to, but not including,stop.range(start, stop): Generates numbers fromstartup to, but not including,stop.range(start, stop, step): Generates numbers fromstartup to, but not including,stop, incrementing bystepeach time.
range() function to print all multiples of 3 between 10 and 20, including 10 and 20 if they are multiples.Iterating Over Dictionaries
Dictionaries store data as key-value pairs, and for loops offer flexible ways to iterate through their contents. By default, when you iterate directly over a dictionary, the loop processes its keys. To access values or both keys and values, Python provides specific dictionary methods. The .keys() method returns an iterable of all keys, .values() returns an iterable of all values, and .items() returns an iterable of key-value pairs as tuples.
For loops automate repetitive tasks by processing each item in a collection.
They iterate over various sequences like lists, tuples, and strings, executing a code block for each element.
The
range()function is crucial for generating numerical sequences, useful for fixed-count loops or index-based iteration.Dictionaries can be iterated over their keys (default), values (using
.values()), or key-value pairs (using.items()).Mastering
forloops is essential for efficiently processing data and controlling program flow.