python function --range () method

range () method

range () built-in function can return python is a series of consecutive integers increases, it works like fragments may generate a list of objects.

Most range function often appear in a for loop, the for loop can be used as an index. In fact, it can also occur in any environment requires integer list,

Python 3.0 in the range function is an iterator. Only one function parameters in the range (), the list represents an integer of from 0 generated counted:

Example:

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

python range (), when the two arguments, then start bit as the first parameter, the second parameter is the final bit:

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

range () function can be filled within the three parameters, the third parameter is the step value (step value defaults to 1):

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

Parameters and results of range function must be a positive number is not incremented or, like 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]

range () role and skills in the for loop

The range may be given number, the operation is repeated, look for a range of circulating the most simple example:

>>> 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 www.cnblogs.com/hanjiali/p/11589535.html