Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

Python random.randint() Method



The random.randint() method in Python random module is used to generate random integer N between a specified range, inclusive of both start and end. This method is an alias for random.randrange(a, b+1) method. This method works with long integers, meaning there is no practical upper limit to the values that can be generated.

Note − To use this randint() method, you need to import the random module as it is not accessible directly, then you need to call the method using the random object.

Syntax

Following is the syntax of python random.randint() method −

randint(start_range,end_range)

Parameters

The Python random.randint() method accepts the following parameters −

  • start_range : It is an integer value that represents the lower bound of the range (inclusive).

  • end_range : It is an integer value that represents the upper bound of the range (inclusive).

Return Value

The Python random.randint() method generates a random integer number between the start_range and end_range.

Example 1

Let us look at an example using python random.randint() method which accepts a particular range of positive numbers as parameters.

import random

# positive number
random_num=random.randint(1,15)
print(random_num) 

Output of the above code is as follows −

6

Note − You will get different random numbers each time you execute the code because random.randint() generates a new random integer within the specified range on each call.

Example 2

Let us consider another example which accepts a particular range of negative numbers as parameters.

import random

# negative number
random_num=random.randint(-10 ,-1)
print(random_num)

Following is the output of the above code −

-5

Example 3

Python random.randint() method can handle very large integers because Python's int type supports unlimited precision.

Let's look into an example of generating a random number within a very large range.

import random

# Generate a random integer between 1 and a very large number
large_number = 1234567890123456789012345678900000347853478734827873827489372348374887365487563478568374677878
random_number = random.randint(1, large_number)

print(random_number)

When we run above program, it produces a value like below −

315337467194547594398046641025869206802441515618762768914103177006160220670619673456458196230

Example 4

The parameters should only be integers. If we pass float values, it will result in value error.

Let us see an example with a range including a float value which results in a value error.

import random

random_num=random.randint(1,5.5)
print(random_num) 

When we run above program, it raises the following error −

ValueError: non-integer stop for randrange()
python_modules.htm
Advertisements