For loops in python

Python, a popular programming language, offers a wide range of features and constructs to simplify and optimize code execution. One such essential feature is loops. Loops allow you to iterate over a sequence of elements, performing repetitive tasks with ease and efficiency. In this article, we will explore the different types of loops in Python 3 and how they can be leveraged to streamline your programming endeavors.

The For Loop:

The for loop is widely used when you have a predefined sequence of elements, such as a list or a range of numbers. It iterates over each item in the sequence and executes a block of code for each iteration. The loop terminates automatically when it reaches the end of the sequence. The for loop is incredibly versatile and allows you to process collections, perform calculations, and more.

The While Loop:

The while loop is useful when you need to repeat a set of statements until a certain condition becomes false. It continuously executes the code block as long as the specified condition holds true. Be cautious, though, as an incorrect condition may result in an infinite loop. To prevent such scenarios, ensure that the loop's condition eventually becomes false.

Nested Loops:

Python supports the concept of nested loops, where one loop is present inside another. This enables you to handle complex scenarios by iterating over multiple sequences simultaneously. Nested loops are particularly useful when working with multidimensional data structures, such as matrices or grids. However, keep in mind that excessive nesting can impact performance, so use them judiciously.

Loop Control Statements:

Python provides two essential loop control statements: break and continue. The break statement allows you to prematurely exit a loop, even if the loop condition is still true. It's useful when you need to terminate a loop based on certain conditions. On the other hand, the continue statement allows you to skip the remaining code in the current iteration and proceed to the next iteration. It is handy when you want to skip specific iterations based on certain conditions.

Looping Through Dictionaries:

Dictionaries are a fundamental data structure in Python, and looping through them requires a slightly different approach. You can iterate over the keys, values, or key-value pairs in a dictionary. By using the keys() method, you can loop through the keys. Similarly, the values() method allows iteration over the values. Lastly, the items() method enables you to loop through both the keys and values simultaneously.

Conclusion:

Loops are an indispensable tool in Python 3 for performing repetitive tasks efficiently. Whether you are working with lists, ranges, dictionaries, or complex data structures, loops enable you to iterate through them effortlessly. By understanding and utilizing the different types of loops available, you can enhance your code's functionality, readability, and performance. So, embrace the power of loops and unlock new possibilities in your Python programming journey.

Python3 loops examples

Iterate a python list

country_list = ['Germany', 'France', 'Italy', 'Spain']
for country in country_list:
    print(country)

Will output:

Germany
France
Italy
Spain

Iterate over a range of numbers

for num in range(1, 6):
    print(num)

Will output:

1
2
3
4
5
Please note that range loop will not reach the last number, in our case 6, it will stop at 5.

Print numbers from 1 to 5 using a while loop

num = 1
while num <= 5:
    print(num)
    num += 1

Print even numbers less than or equal to 10 using a while loop

num = 2
while num <= 10:
    print(num)
    num += 2

Nested loops

# Multiplication table using nested loops
for i in range(1, 11): # not the range up to 11 it will actually be up to 10 inclusive
    for j in range(1, 11):
        print(i * j, end="\t")  # Use "\t" for tab spacing
    print()  # Move to the next line after each row

Iterate a python dictionary

country_dict = {
    'Germany': 'Berlin',
    'France': 'Paris',
    'Italy': 'Rome',
    'Spain': 'Madrid',
}
for key in country_dict:
    print('{1} is the capital of {0}'.format(
        key,
        country_dict[key]
    ))

The output will be:

Berlin is the capital of Germany
Paris is the capital of France
Rome is the capital of Italy
Madrid is the capital of Spain

Looping through dictionaries

# Iterate over keys in a dictionary
person = {"name": "John", "age": 30, "city": "New York"}
for key in person:
    print(key)

# Iterate over values in a dictionary
for value in person.values():
    print(value)

# Iterate over key-value pairs in a dictionary
for key, value in person.items():
    print(key, ":", value)

Iterate a python dictionary with enumerate

for item in enumerate(country_dict):
    print(item)

The value for item will be:

(0, 'Germany')
(1, 'France')
(2, 'Italy')
(3, 'Spain')

As you can see, item will be an item where the first element is the index number and the second element is the dictionary key value for each iteration. To get the capital city for each country using enumerate write:

for item in enumerate(country_dict):
    print('({0}) {2} is the capital of {1}'.format(
        item[0],                # interation index
        item[1],                # dictionary key
        country_dict[item[1]]   # dictionary value for the current key
    ))

The output will be:

(0) Berlin is the capital of Germany
(1) Paris is the capital of France
(2) Rome is the capital of Italy
(3) Madrid is the capital of Spain

Using break to stop a for loop

Let's say we want to iterate only first two elements from our dictionary:

for item in enumerate(country_dict):
    if item[0] > 1:
        break
    print('({0}) {2} is the capital of {1}'.format(
        item[0],                # interation index
        item[1],                # dictionary key
        country_dict[item[1]]   # dictionary value for the current key
    ))

The above code will iterate through the dictionary and will stop after the first two interations. Keep in mind that the first iteration has the index zero (0) and the second interation has the index one (1). This is why the condition is if item[0] > 1:. To stop the iteration of the dictionary we use the break statement.

The output will be:

(0) Germany is the capital of Berlin
(1) France is the capital of Paris

Using continue to skip elements

Let's say that you have a list if dictionaries with the country details but you want to display some information only for one of them:

countries_list = [
    {
        'name': 'Germany',
        'country_code': 'DE',
        'capital': 'Berlin',
    },
    {
        'name': 'France',
        'country_code': 'FR',
        'capital': 'Paris',
    },
    {
        'name': 'Italy',
        'country_code': 'IT',
        'capital': 'Rome',
    },
    {
        'name': 'Spain',
        'country_code': 'ES',
        'capital': 'Madrid',
    },
]

If you will loop through the countries list, you will write:

for country_dict in countries_list:
    print(country_dict)

and the output will be

{'name': 'Germany', 'country_code': 'DE', 'capital': 'Berlin'}
{'name': 'France', 'country_code': 'FR', 'capital': 'Paris'}
{'name': 'Italy', 'country_code': 'IT', 'capital': 'Rome'}
{'name': 'Spain', 'country_code': 'ES', 'capital': 'Madrid'}

Each element of the iteration will be of type dict (dictionary).

If you are interested to get the details for Italy only, you'll write the for loop like this:

for country_dict in countries_list:
    if country_dict['country_code'] != 'IT':
        continue
    print(country_dict)

The output will be:

{'name': 'Italy', 'country_code': 'IT', 'capital': 'Rome'}

With the above core, you have to take in consideration that the for loop will not stop when it will find the required element. It will continue the iteration for all elements in the list and will skip everything that doesn't satisfy the condition from if statement

To stop the iteration you'll have to use break

for country_dict in countries_list:
    if country_dict['country_code'] != 'IT':
        continue
    print(country_dict)
    break

Or you can change the if condition to a positive form. But doing this, continue will not be necessary any more:

for country_dict in countries_list:
    if country_dict['country_code'] == 'IT':
        print(country_dict)
        break

The output will be the same as above


Using else in a for loop statement

Let's take the last example and look for a country that is not in our list. If the required element was not found, then I want to know about it:

for country_dict in countries_list:
    if country_dict['country_code'] == 'RO':
        print(country_dict)
        break
else:
    print('Required country was not found')

The output will be:

Required country was not found

Now, the tricky part.

The code from else block will be executed when the for loop will finish. The break statement here, makes the for loop NOT to enter into else statment.

If we search for IT for example and remove the break statement to allow to iterate through all elements of the list:

for country_dict in countries_list:
    if country_dict['country_code'] == 'IT':
        print(country_dict)
else:
    print('Required country was not found')

The output will be:

{'name': 'Italy', 'country_code': 'IT', 'capital': 'Rome'}
Required country was not found
Note that break is not anymore below print(country_dict). This will make for loop to continue iteration until the end. Once it finishes, it will enter in else block