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 = "www.freelearningpoints.com" #for looping through the add string for i in website: print (i, end = "")
The output is:
www.freelearningpoints.com
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.
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:
5050
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
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.
Example:
dic_1 = {'python tutorial': " http://www.freelearningpoints.com/python/tutorials/ ", 'Python exercise': " http://www.freelearningpoints.com/python/exercises/basic"} for i in dic_1: print ('Dictionary =', i)
The output is:
Dictionary = python tutorial
Dictionary = Python exercise
More Tutorials:
Python Installation - Linux (Ubuntu)More Python Exercises:
Python String Exercises