Home > Backend Development > Python Tutorial > Basic usage of range function in Python

Basic usage of range function in Python

尊渡假赌尊渡假赌尊渡假赌
Release: 2024-01-26 15:17:59
Original
1481 people have browsed it

Range() in Python is a built-in function used to generate an integer sequence. Its basic syntax is "range(start, stop[, step])", where start represents the starting value of the sequence ( Can be omitted, default is 0), stop represents the end value of the sequence (must be specified), step represents the step size between two adjacent numbers in the sequence (can be omitted, default is 1).

Basic usage of range function in Python

#In Python, range() is a built-in function used to generate a sequence of integers. The basic syntax of the range() function is as follows:

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

Among them, start represents the starting value of the sequence (can be omitted, the default is 0), stop represents the end value of the sequence (must be specified), and step represents the phase in the sequence. The step size between two adjacent numbers (can be omitted, default is 1).

The range() function returns an iterator, which can be converted into a list using the list() function. For example:

sequence = range(1, 10, 2)
print(list(sequence))
# 输出:[1, 3, 5, 7, 9]
Copy after login

In the above code, range(1, 10, 2) generates a sequence containing 1, 3, 5, 7, 9, through list() The function converts it to a list and outputs it.

It should be noted that the first parameter stop of the range() function is required, while the second parameter start and the third parameter step are optional. If the start parameter is omitted, it defaults to starting at 0. If the step parameter is omitted, the default step size is 1.

In addition, it should be noted that the sequence generated by the range() function is a left-closed and right-open interval, that is to say, the sequence contains the starting value but not the ending value. For example, the sequence generated by range(1, 5) is 1, 2, 3, 4, excluding 5.

In short, the range() function is the basic function in Python for generating integer sequences. By specifying the starting value, end value and step size, any integer sequence can be generated.

The above is the detailed content of Basic 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