How to Use Python range() Function?

Share This Post

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

spot_img

Related Posts

Python for Loop Iteration: How to Easily Manipulate a List

One of the most powerful features of the Python...

How To Get First Characters of a String in Python

Way to find the first characters of a string...

How To Convert Tuple To String In Python

In this post, you will learn how to convert...

How To Convert String to Double in Python

Good to hear, that you want to convert a...

Python TypeError: String Index Out Of Range Solution

A string is an array of characters and part...

How To Remove Empty Strings From a List Of Strings

On this page, we will discuss how to remove...
- Advertisement -spot_img