Python function tutorial: range() method

range() is a python built-in function that returns a series of continuously increasing integers. It works like slicing and can generate a list object.

The range function most often appears in for loops, and can be used as an index in for loops. In fact it can also appear in any environment that requires a list of integers,

In python 3.0 the range function is an iterator. There is only one parameter in the range() function, which means that a list of integers starting from 0 will be generated:

Example :

>>> range(5)
[0, 1, 2, 3,4] #python 返回值

In python range(), when two parameters are passed in, the first parameter is used as the start bit, and the second parameter is the end bit:

>>> range(0,6)
[0, 1, 2, 3, 4,5]

Three parameters can be filled in the range() function, and the third parameter is the step value (the default step value is 1):

>>> range(0,10,2)
[0, 2, 4, 6,8]

The parameters and results of the range function do not have to be positive or increasing, such as the following two examples:

>>> range(-4,4)
[-4, -3, -2, -1, 0, 1, 2, 3]
>>>
>>> range(4,-4,-1)
[4, 3, 2, 1, 0, -1, -2, -3]

The role and skills of range() in for loop

The range can repeat the action according to a given number of times. Let's look at the simplest example of a range and for loop:

>>> x = 'playpython'
>>> for i in x:
...   print(i)
... 
 p l a y p y t h o n
>>> range(len(x))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> len(x)
10
>>> for i in range(len(x)):
...   print(x[i])
... 
 p l a y p y t h o n

Guess you like

Origin blog.csdn.net/m0_67575344/article/details/124256641