Skip to content

How to Use Python range() Function?

  • by
use Python range() Function

Iterating sequence types (Python range() List, string, etc.) With for and while loops is the most popular application of the range() method in Python so let’s go and use python range() function.

Use Python range() Function

  • You can use range() in three different ways:
  • There is only one parameter to range(stop).
  • Here are two arguments to range(start, stop).
  • There are three arguments to range(start, stop, step).

The reach() method returns a numeric sequence that begins at 0 and increases by 1 (by default) until it surpasses the value.

Syntax

  • range(start, stop, step)
  • Values of Parameters
  • Parameter Description \sstart
  • Start Optional. The starting point is specified by an integer number. The default setting is 0 stop. Required.
  • Stop: The position at which to halt is indicated by an integer number (not included).
  • Step: Optional. The incrementation is specified by an integer number. 1 is the default value.

Example

Make an alphanumeric code from 3 to 5, then print each item in the sequence:

x = range(3, 6)
for n in x:
 	print(n)

Output

3
4
5

Use Python range() Function

Make an alphanumeric code from 3 to 19, but instead of 1 increment, use 2:

x = range(3, 20, 2)
for n in x:
	print(n)

Output

3
5
7
9
11
13
15
17
19

Use Python range() Function

Use the Python if statement with the in keyword to see if a given integer is within a range, as demonstrated below. The expression number in range() returns a boolean value: True if the number appears in range(), False if the number does not appear in range(). You may also use not to the existing syntax to check the opposite way around.

The most frequent form is range(n), which produces a number series beginning with 0 and continuing with n but not containing it, e.g. range(5) returns 0, 1, 2, 3, 4. Alternatively, range(n) returns a sequence of n numbers beginning with 0.

Read more: 3 Best Ways to Exit a Python Program

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *