Home > Backend Development > Python Tutorial > What is the usage of range function in python

What is the usage of range function in python

coldplay.xixi
Release: 2023-01-03 09:28:10
Original
127807 people have browsed it

Usage of range function in python: [range()] function can create a list of integers, generally used in for loops. The function syntax is [range(start, stop[, step])], where start is Start counting, stop means stop, and step means step size.

What is the usage of range function in python

The operating environment of this tutorial: Windows 7 system, python version 3.9, DELL G3 computer.

Usage of range function in python:

range() function can create a list of integers and is generally used in for loops.

Note: Python3 range() returns an iterable object (type is object), not a list type, so the list will not be printed when printing.

Function syntax

range(start, stop[, step])
Copy after login

Parameter description:

  • start: Counting starts from start. The default is to start from 0. For example, range(5) is equivalent to range(0, 5);

  • stop: counts to the end of stop, but does not include stop. For example: range (0, 5) is [0, 1, 2, 3, 4] without 5

  • step: step size, default is 1. For example: range(0, 5) is equivalent to range(0, 5, 1)

Example

>>>range(10)        # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3)  # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
Copy after login

The following is the use of range in for, loop out Each letter of runoob:

>>>x = 'runoob'
>>> for i in range(len(x)) :
...     print(x[i])
... 
r
u
n
o
o
b
>>>
Copy after login

Related free learning recommendations: python video tutorial

The above is the detailed content of What is the usage of range function in python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template