Home >Backend Development >Python Tutorial >A brief introduction to the for loop and range() function in Python (with examples)
This article brings you a brief introduction to the for loop and range() function in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
for loop
The For … in statement is another type of loop statement, which is characterized by executing on a series of objects Iterates, that is, it will traverse each item in the sequence
Note:
1. The else part is optional Chosen. When it is included in a loop, it always starts execution after the for loop ends, unless the program encounters a break statement.
2. for... in can work in any queue. Some generate a list of numbers through the built-in range function, or it can be a queue containing any type of object.
Eg1.数字列表 for i in range(1,5): print(i) else: print("for 循环结束")
Eg2. 字符串列表 lessons = ["语文","数学","英语"] for lesson in lessons: print("------------------"+'\n'+lesson) else: print("------------------") print("for 循环结束")
range() function
General form: range(start, stop[, step] )
start: Start value, the value is 0, that is, if this item is not written, start = 0 is considered.
stop: The ending value, this must be written.
step: The step size of the change, the default is 1.
Eg. # range 类型 a = list(range(10,0,-1)) print(a)
Parallel iteration
Iteration, the performance in Python is to use a for loop to obtain a certain amount from the object quantity of elements.
Use for loops for key-value pairs of lists, strings, and dictionaries. This is iteration.
#The parameter of Zip() needs to be an iterable object. The return value of the Zip function is a zip object.
Eg1. 两个列表中值对应相加 a = [1,2,3,4,5] b = [9,8,7,6,5] c= [] for x,y in zip(a,b): d.append(x+y) else: print(d)rrree
The above is the detailed content of A brief introduction to the for loop and range() function in Python (with examples). For more information, please follow other related articles on the PHP Chinese website!