⊗pyPmLpFrI 146 of 208 menu

For loop in Python

Loops are designed to perform the same operation over and over, such as looping through elements. iterable objects. Such objects include strings, tuples, lists, sets, and dictionaries.

The most widely used loop in Python is the for loop. Its syntax is:

for element in iterable object: loop body

In the for cycle, as well as in the if-else construction, one indentation must be made under the block with the condition for the code located below.

Let us have a list lst:

lst = [1, 2, 3, 4, 5]

Let's use the for loop to iterate over and output all its elements:

lst = [1, 2, 3, 4, 5] for el in lst: print(el) # 1, 2... 5

In the body of the loop, you can perform various operations on the elements. Let's output the squares of the element values:

for el in lst: print(el ** 2) # 1, 4... 25

Given a list:

tst = ['1', '2', '3', '4', '5']

Loop through it and output each element to the console.

A tuple is given:

tst = (1, 2, 3, 4, 5)

Loop through it and output each element to the console.

Given a set:

tst = {'a', 'b', 'c', 'd', 'e'}

Loop through it and output each element to the console.

Given a string:

tst = 'abcde'

Loop through it and print each character to the console.

Given a number:

tst = 12345

Loop through it and print each digit to the console.

Given a list:

tst = [1, 2, 3, 4, 5]

Add 2 to each of its elements and print the result to the console.

byenru