Python – For Loop

There are two types of loop statements in Python, while loops and for loops. The previous chapter has explained the while loop. This section introduces for loop. It is commonly used to traverse strings, lists, tuples, dictionaries, collection and other sequence types, get each element in the sequence one by one.

The syntax of a for loop is as follows:

for iteration variable in string | list | tuple | dictionary | collection:
   Code block

In the format, the iteration variable is used to store the elements read from the sequence type variable, so the iteration variable is generally not manually assigned in the loop; the code block refers to multiple lines of code with the same indentation format (same as while ), Because it is used in conjunction with the loop structure, the code block is also called the loop body.

The execution flow of the for-loop statement is shown in the following figure.

website = ""
#for looping through the add string
for i in website:
    print (i, end = "")

The output is:

It can be seen that during the traversal of the website string using a for loop, the iteration variable i is successively assigned to each character in the website string and is used in the loop body. It's just that the loop body in the example is relatively simple, with only one line of output statements.

Specific Application of Python For Loop

Python For Loop - Numerical

When using a for loop, the most basic application is numerical looping. For example, if you want to accumulate from 1 to 100, you can execute the following code:

print ("The result of calculating 1 + 2 + ... + 100 is:")
#Save the accumulated variable
result = 0
#Get the values from 1 to 100 one by one and do the accumulation operation
for i in range (101):
    result += i
print (result)

The output is:

The result of calculating 1 + 2 + ... + 100 is:

Python For Loop - Lists and Tuples

When using a for loop to traverse list or tuple, its iteration variable will be assigned to each element in the list or tuple and the loop body will be executed once.

The following program traverses a list using a for loop:

my_list = [1,2,3,4,5]
for i in my_list:
    print ('nums=', i)

The output is:

nums= 1
nums= 2
nums= 3
nums= 4
nums= 5

Python For Loop - Dictionary

When using for loop to traverse a dictionary, three dictionary-related methods are often used, namely items, keys, and values . Their respective usages have been described in the previous chapters, and will not be repeated here. Of course, if you use a for loop to traverse the dictionary directly, the iteration variable will be assigned to the key in each key-value pair.


dic_1 = {'python tutorial': " ",
          'Python exercise': ""}
for i in dic_1:
    print ('Dictionary =', i)

The output is:

Dictionary = python tutorial
Dictionary = Python exercise


More Tutorials:

Python Installation - Linux (Ubuntu)
Python Installation - Mac OS
Integrated Development Environment - IDE
Python - Basic Variables
Python - Sequence Introduction
Python - Output Formatting
Python - Escape Character
Python - Type Conversion
Python - Numbers
Python – Arithmetic Operators
Python – Assignment Operators
Python – Comparison Operators
Python – Logical Operators
Python – Precedence and Associativity Operators
Python – Bytes Type and Usage
Python – Long & Raw Strings
Python – Concatenate Function
Python – Slice Function
Python – Length and Split Function
Python – Join and Count Function
Python – Find Function
Python – Index Function
Python – Alignment Function
Python – Startswith and Endswith Function
Python – String Case Conversion
Python – Remove Specified Character
Python – Encode and Decode Function
Python – dir and help Function
Python – Input Output Introduction
Python – Basic Operation
Python – Open Function
Python – Read Function
Python – Readline Function
Python – Write Function
Python – Close Function
Python – Seek and Tell Function
Python – Pickle Module
Python - File Input Module and Linecache Module
Python - Pathlib Module
Python - Pathlib Module
Python - os.path Module
Python - fnmatch Module
Python - Tuple Introduction
Python - List Introduction
Python - List Add Element
Python - List Delete Element
Python - List Modification Element
Python - List Find Element
Python - Dictionary Introduction
Python - Dictionary Basic Operation
Python - Dictionary Method Guide
Python - Set Collection
Python - Set Basic Operation
Python - Set Basic Method
Python - Frozenset Method
Python - If Condition I
Python - If Condition II
Python - While loop
Python - For loop
Python - Pass Statement
Python - Break Statement
Python - Zip Reverse Function
Python - Function Introduction
Python - Positional Parameters
Python - Key Arguments
Python - None and Return
Python - Variable Scope
Python - Local Function
Python - Closure Method
Python - Lamdba Expression

More Python Exercises:

Python String Exercises
Python List Exercises
Python Library Exercises
Python Sets Exercises
Python Array Exercises
Python Condition Statement Exercises