[ad_1]

Loops are one of the fundamental concepts of programming languages. Loops are used to perform repeated tasks until a certain condition is met.

There are two main looping constructs in Python that allow you to repeat a block of code repeatedly, the for and the while
loops.

In this article, we will cover the basics of the for loops in Python. We will also show you how to use the range
type to generate a sequence of numbers, and else, break and continue statements to alter the flow of a loop.

Python for Loop

The for loop in Python iterates over the items of a sequence and repeatedly executes a block of statements.

The Python for loop takes the following form:

for item in sequence:
  statements

The for statement starts with the for keyword, then a variable (item) to assign each item of the sequence to (loop control target), followed by the in keyword, and finally the sequence. Each conditional statement ends with a colon (:).

The statements block starts with an indentation and ends with the first unindented line. Most people choose to use either 4-space or 2-space indentation. The official Style Guide for Python Code
recommends to use 4-spaces per indentation level and to avoid mixing the use of tabs and spaces for indentation.

Here is an example:

berries = ["Blueberry", "Raspberry", "Strawberry"]

for berry in berries:
  print(berry)
Blueberry
Raspberry
Strawberry

You can iterate over any sequence such as a string, a list, a dictionary, or a tuple.

In the code below, we’re iterating through the characters in the string ‘linux’:

for x in 'linux':
  print(x)
l
i
n
u
x

When looping through a dictionary, the variable is assigned to the key:

berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}

for key in berries:
  print(key)
Blueberry
Raspberry
Strawberry

To access the values of the dictionary, use the key’s index:

berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}

for key in berries:
  print(berries[key])

Another option to loop trought the dictionary’s values is to use the values() method:

berries = {'Blueberry': 100, 'Raspberry': 125, 'Strawberry': 150}

for value in berries.values():
  print(value)

The output of both examples is the same:

100
125
150

The range() Constructor

The Python range() constructor allows you to generate a sequence of integers by defining the start and the end point of the range. range() works differently in Python 2 and 3. In this article, we are using Python 3.

range() is typically used with the for loop to iterate over a sequence of numbers. This is a Python equivalent of the C-style for loop.

for i in range(3):
  print(i)
0
1
2

When two arguments are provided, range returns a sequence of numbers, incremented by 1, starting from the first argument to second argument - 1:

for i in range(3, 5):
  print(i)
3
4

The third argument allows you to specify an increment:

for i in range(0, 16, 5):
  print(i)
0
5
10
15

Nested for Loop

A nested loop is a loop inside another loop. They are often used to handle iterable object that contains iterable elements:

for i in range(0, 6):
  for j in range(0, 6):
    print('%d + %d = %d' % (i, j, i+j))
0 + 0 = 0
0 + 1 = 1
0 + 2 = 2
...
5 + 3 = 8
5 + 4 = 9
5 + 5 = 10

The break and continue Statements

The break and continue statements allow you to control the execution of the for loop.

break Statement

The break statement terminates the current loop and passes the program control to the statement that follows the loop. When used inside a nested loop, the break statement terminates the innermost loop.

In the following example, we are using the if
statement to terminate the execution of the loop once the current iterated item is equal to ‘Raspberry’:

for i in ["Blueberry", "Raspberry", "Strawberry"]:
  if i == "Raspberry":
    break
  print(i)
Blueberry

continue Statement

The continue statement exits the current iteration of the loop and passes the program control to the next iteration of the loop. The loop is not terminated; only the current iteration is skipped.

In the following example, we are iterating through a range of numbers. When the current iterated item is equal to ‘3’, the continue statement will cause execution to return to the beginning of the loop and to continue with the next iteration:

for i in range(1, 6):
  if i == 3:
    continue
  print(i)
1
2
4
5

The else Clause

In Python, the for loop can have an optional else clause.

The else clause is executed when the loop finishes normally, i.e when all iterables are exhausted:

for i in ["Blueberry", "Raspberry", "Strawberry"]:
  print(i)
else:
  print('Loop completed.')
Blueberry
Raspberry
Strawberry
Loop completed.

When the loop is terminated with break or continue statements, the else clause is not executed:

for i in ["Blueberry", "Raspberry", "Strawberry"]:
  if i == "Raspberry":
    break
  print(i)
else:
  print('Loop completed.')
Blueberry

Conclusion

The Python for loop is used to repeatedly execute a block of code for a fixed number of times.

If you have any questions or feedback, feel free to leave a comment.

[ad_2]

Source link

Related Posts

Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.