Functions that can be used in for statements
Python uses a for statement to iterate over. If you want to perform processing such as repeating by specifying the number of times, combine it with the range function.
range () function Returns a series of numbers starting at 0 and incrementing or decrementing by 1 (default), stopping before the specified number. range (start, end, step)
How to use | Description |
---|---|
start | An integer that specifies the starting position. The default is 0. |
End | An integer that specifies the post-end position. |
Step | An integer that specifies increment and decrement. The default is 1. |
Start An integer that specifies the start position. The default is 0. End An integer that specifies the position after the end. Step Increment, an integer that specifies decrement. The default is 1.
range (start, end, step)
for f in renge(5)
print (f, end = ‘ ’)
01234 Since the value specified for "End" is not included, 4 is returned. If you want to get up to 5, you can specify 6.
range(1, 5, 2)
range(10, 5, -2)
print(list(range(3))) With this form, it seems that you can get it as a list type.
Loop counter I'm ashamed to say that I didn't know the meaning of the loop counter, so I looked it up. A variable that controls the loop. Used when the end condition of the iterative process is the number of processes, the loop counter is incremented by 1 each time the process is performed, and the number of times the process is performed is counted and controlled. .. The above meaning is called a loop counter.
If you want to use the loop counter in Python, use the enumerate () function.
enumerate()
l = [‘kokugo’, ‘suugaku’, ‘eigo’]
for i, subject in enumerate(l): print(i, subject) 0 kokugo 1 suugaku 2 eigo
If the second argument is specified as shown below, the loop counter is returned from the specified value.
l = [‘kokugo’, ‘suugaku’, ‘eigo’]
for i, subject in enumerate(l, 11): print(i, subject) 11 kokugo 12 suugaku 13 eigo
zip() Loop counters can also be defined using the zip () function
for i , w in zip(['kokugo', 'suugaku', 'eigo'], [78, 82, 54]): print(subject, number) kokugo 78 suugaku 82 eigo 54
It is also possible to define the loop contents with variables as shown below.
subject = ['kokugo', 'suugaku', 'eigo'] number = [78, 82, 54]
for i , w in zip(subject, number): print(subject, number) kokugo 78 suugaku 82 eigo 54
Recommended Posts