Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python random.randint() Method



Therandom.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 forrandom.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 Pythonrandom.randint() method generates a random integer number between the start_range and end_range.

Example 1

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

import random# positive numberrandom_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 becauserandom.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 numberrandom_num=random.randint(-10 ,-1)print(random_num)

Following is the output of the above code −

-5

Example 3

Pythonrandom.randint() method can handle very large integers because Python'sint 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 numberlarge_number = 1234567890123456789012345678900000347853478734827873827489372348374887365487563478568374677878random_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 randomrandom_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
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp