English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Le type range() retourne une séquence de nombres constants entre l'entier de départ et l'entier de fin donné.
Le constructeur de range() a deux formes de définition :
range(stop) range(start, stop[, step])
range() utilise principalement trois paramètres qui ont la même utilisation dans les deux définitions :
start -entier, à partir duquel la séquence d'entiers est retournée
stop-pour retourner l'entier de la séquence à retourner
l'intervalle de nombres entiers entre1deà l'extrémité du point final.
step (optionnel) -valeur entière, déterminant l'incrément entre chaque entier de la séquence
range() retourne un objet de séquence de nombres immutable, selon la définition utilisée :
retourne à partir de0tostop-1une séquence de nombres
sistoppourun nombre négatif ou nul,alors, retourne une séquence vide.
The return value is calculated according to the following formula under the given constraints:
r[n] = start + step*n (for both positive and negative step) where, n >=0 and r[n] < stop (for positive step) where, n >= 0 and r[n] > stop (for negative step)
(ifstep)step defaults to1。Returns fromstarttostop-1ending number sequence.
(ifstep is zero)raisesValueErrorException
(if step is not zero)checkValue constraintWhether it meets the constraint and returns the sequence according to the formula.
If the value constraint is not met, it returnsEmpty Sequence。
# Empty range print(list(range(0))) # Use range(stop) print(list(range(10))) # Use range(start, stop) print(list(range(1 10)))
When running the program, the output is:
[] [0, 1 2 3 4 5 6 7 8 9] [1 2 3 4 5 6 7 8 9]
Note:We have converted the range toPython list,because range() returns an object similar to a generator, which prints output on demand.
However, the range object returned by the range constructor can also be accessed by its index. It supports both positive and negative indices.
You can access the range object by index as follows:
rangeObject[index]
start = 2 stop = 14 step = 2 print(list(range(start, stop, step)))
When running the program, the output is:
[2 4 6 8 10 12]
start = 2 stop = -14 step = -2 print(list(range(start, stop, step))) # Not satisfied with value constraints print(list(range(start, 14, step)))
When running the program, the output is:
[2, 0, -2 -4 -6 -8 -10 -12] []