Python For Loops With Examples
Today, we’ll learn about Python for loops with examples as part of our learning objectives.
Python For Loops
Python for loops iterates over sequences (which can be lists, tuples, dictionaries, sets, or strings).
It works more like an iterator method in object-oriented programming languages than the for keyword in other programming languages.
For each item in a list, tuple, set, etc., a for loop executes a set of statements.
In a list of tech firms, print each firm as follows:
There is no need to set an indexing variable before using the for loop.
For Loop With A String
Python for loops use iterable objects, including strings, which contain sequences of characters:
Iterate through each letter of the word “yourname”:
Python break For Loop
When trying to loop through all the items in a Python for loop, we can stop it with a break statement:
This loop will be terminated when mrx equals “yourname”:
This time, the break is before the print, so it will exit the loop when mrx is “yourname”:
Python range() Function
Python range() function allows us to loop through code a given number of times.
You can pass up to three arguments to range():
range(start, stop, step)
- Start is the first argument.
- Stop is the second argument.
- Lastly, there is Step.
Let’s take a look at range() in the context of multiple arguments.
A range() function in Python returns a sequence of numbers starting at zero by default, and incrementing by one (by default), ending at the specified number.
Here are some examples of how to use range():
It is important to note that range(4) is not the range of 0 to 4, but the range of 0 to 3.
In range(), the starting value is 0, but a parameter can be used to specify a value starting from 1 to 4 (but not including 4):
The start parameter is used as follows:
Default behavior of the range() function is to increment the sequence by one.
A third parameter can be added to specify the increment value: range(2, 20, 2):
Set the sequence to 2 (the default is 1):
Python continue Statement
In Python for loops, the continue statement allows us to stop the current iteration and continue with the next:
Keep Elon Musk out of print:
Python Nested Loops
Nesting is the act of creating a loop inside another loop.
Each iteration of the “outer loop” will execute the “inner loop” once:
For every firm, print each adjective:
Python For Else Loop
For loops with an else statement, set a block of code to run when the loop ends:
Once For loop is complete, print all the numbers from 0 to 4, and a message:
A break statement will stop the loop without executing the else block.
Let’s see what happens when mrx is 5 and the else block is executed:
Pass In Python
Python for loops cannot be blank, but if you have a for loop with no content, include the pass statement to prevent returning an error.
Python For Loop Usage
Although the For loop is used widely in the python programming to conquer different tasks, some of the uses of it are given below:
- The for loop in Python is commonly used to iterate over a sequence of elements such as lists, strings, tuples, or other iterable objects. It allows you to access each element in the sequence one by one, making it easier to perform operations on them.
- In addition to iterating over the elements themselves, the for loop can also be used to access the indices of the elements in the sequence. By using the
enumerate()function, you can retrieve both the index and the corresponding element during each iteration, which can be useful when you need to perform operations based on the index or modify elements in the sequence.
- The for loop can be used to repeat a block of code a specific number of times. Instead of iterating over a sequence, you can use the
range()function to generate a sequence of numbers and iterate over them using the for loop. This is particularly useful when you need to execute a certain set of instructions a predetermined number of times, such as in counting loops or when implementing algorithms.
- The for loop can iterate over dictionaries in Python, allowing you to access both the keys and values of each key-value pair. By default, the loop iterates over the keys of the dictionary, but you can use the
.items()method to iterate over both the keys and values simultaneously. This enables you to perform operations based on the key-value pairs or extract information from dictionaries.
- Python’s for loop can be nested within another loop, allowing you to create complex iterations. This is useful when you need to iterate over multiple sequences simultaneously or when you want to generate combinations or permutations of elements. Nested loops provide a powerful mechanism to handle multidimensional data structures and implement advanced algorithms and computations.