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


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:

Example

firms = ["Tesla", "IBM", "Google"] for mrx in firms: print(mrx)

Python For Loops example

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”:

Example

for mrx in "yourname": print(mrx)

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”:

Example

firms = ["Tesla", "IBM", "Google"] for mrx in firms: print(mrx) if mrx == "yourname": break

This time, the break is before the print, so it will exit the loop when mrx is “yourname”:

Example

firms = ["Tesla", "IBM", "Google"] for mrx in firms: if mrx == "yourname": break print(mrx)

Python range() Function

Python range() function allows us to loop through code a given number of times.

Range Syntax:

You can pass up to three arguments to range():

range(start, stop, step)
  1. Start is the first argument.
  2. Stop is the second argument.
  3. 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():

Example

for mrx in range(3): print(mrx)

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:

Example

for mrx in range(1, 4): print(mrx)

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):

Example

for mrx in range(2, 20, 2): print(mrx)

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:

Example

ceo = ["Elon Musk", "Mark Zuckerberg", "Sundar Pichai"] for mrx in ceo: if mrx == "Elon Musk": continue print(mrx)

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:

Example

ceo = ["Elon Musk", "Mark Zuckerberg", "Sundar Pichai"] firms = ["Tesla", "Facebook", "Google"]for mrx in ceo: for ample in firms: print(mrx, ample)

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:

Example

for mrx in range(5): print(mrx) else: print("This message is rendering after loop")

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:

Example

for mrx in range(8): if mrx == 5: break print(mrx) else: print("This Else statement will not execute.")

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.

Execute

Example

for mrx in [0, 1, 2, 3]: pass

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:

  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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.
Help us improve this site by leaving your reaction below. We appreciate your thoughts and suggestions.
We value your feedback.
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

Subscribe To Our Newsletter
Enter your email to receive a weekly round-up of our best posts. Learn more!
icon

Leave a Reply

Your email address will not be published. Required fields are marked *