A Python for loop can traverse any sequence of items, such as a list or a string.
The syntax structure for the For loop is as follows:
For Iterating_var in sequence:
Statements(s)
The simplest form is as follows, looping 10 times.
1 for in range:2 print("loop:", i)
Output to
1 loop:0 2 loop:1 3 loop:2 4 loop:3 5 loop:4 6 loop:5 7 Loo P:6 8 loop:7 9 loop:8 loop:9
Range () function
function Prototypes : Range (start, end, scan):
parameter meaning : Start: Count starts from start. The default is starting from 0. For example, range (5) is equivalent to range (0, 5);
End: The technology ends with end, but does not include end. For example: Range (0, 5) is [0, 1, 2, 3, 4] No 5
Scan: The distance between each jump, the default is 1, is called the "step". Example: Range (0, 5) is equivalent to range (0, 5, 1)
1 # represented from 1 to 5 (not including 5) 2 [1, 2, 3, 4]3# represents from 1 to 5, Interval 2 (not 5)4 [1, 3]5 # represented from 0 to 5 (not including 5) 6 [0, 1, 2, 3, 4]
The Len () function is used to calculate the number of elements.
For loop
For loop in can also be followed by a lot of things. Can be followed by a string, tuple, list.
1 forLetterinch 'Python':#First Instance2 Print('Current Letter:', letter)3 4Fruits = ['Banana','Apple','Mango']5 forFruitinchFruits#a second instance6 Print('Current Letter:', fruit)
Output
1 Current Letter: P 2 Current Letter: Y 3 Current Letter: T 4 Current Letter: H 5 Current Letter: o 6 Current letter: N 7 Current Letter: Banana 8 Current Letter: Apple 9 Current Letter: Mango
Continue, break, and else usages are the same as while.
Python for Loop