The Wayback Machine - https://web.archive.org/web/20240524235948/https://www.geeksforgeeks.org/python-randint-function/
Open In App

randint() Function in Python

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

randint() is an inbuilt function of the random module in Python3. The random module gives access to various useful functions one of them being able to generate random numbers, which is randint().  In this article, we will learn about randint in Python.

Python randint() Method Syntax

Syntax: randint(start, end)

Parameters : 

(start, end) : Both of them must be integer type values.

Returns : 

A random integer in range [start, end] including the end points.

Errors and Exceptions :

ValueError : Returns a ValueError when floating point values are passed as parameters.

TypeError : Returns a TypeError when anything other than numeric values are passed as parameters.

How randint() in Python work?

In this example, we are using the randint() method in Python to find a random number in a given range.

Python3




# Python3 program explaining work
# of randint() function
 
# imports random module
import random
 
# Generates a random number between
# a given positive range
r1 = random.randint(0, 10)
print("Random number between 0 and 10 is % s" % (r1))
 
# Generates a random number between
# two given negative range
r2 = random.randint(-10, -1)
print("Random number between -10 and -1 is % d" % (r2))
 
# Generates a random number between
# a positive and a negative range
r3 = random.randint(-5, 5)
print("Random number between -5 and 5 is % d" % (r3))


Output

Random number between 0 and 10 is 2
Random number between -10 and -1 is -7
Random number between -5 and 5 is -3


The randint() Method Example

Multiple Randint Python Method Calls

In this example, we are making multiple random.randint() method calls in Python.

Python3




import random
beg,end=1,1000
for i in range(5):
    print(random.randint(beg, end))


Output

94
550
236
145
747


Program to Demonstrate the ValueError

In this example, we are seeing that if we passes the floating point values as parameters in the randint() function then a ValueError occurs.

Python3




# imports random module
import random
 
'''If we pass floating point values as
parameters in the randint() function'''
 
r1 = random.randint(1.23, 9.34)
print(r1)


Output :

Traceback (most recent call last):
  File "/home/f813370b9ea61dd5d55d7dadc8ed5171.py", line 6, in 
    r1=random.randint(1.23, 9.34)
  File "/usr/lib/python3.5/random.py", line 218, in randint
    return self.randrange(a, b+1)
  File "/usr/lib/python3.5/random.py", line 182, in randrange
    raise ValueError("non-integer arg 1 for randrange()")
ValueError: non-integer arg 1 for randrange()

Program to Demonstrate the TypeError

In this example, we can see that if we pass string or character literals as parameters in the randint() function then a TypeError occurs.

Python3




# imports random
import random
 
'''If we pass string or character literals as
parameters in the randint() function'''
 
r2 = random.randint('a', 'z')
print(r2)


Output : 

Traceback (most recent call last):
  File "/home/fb805b21fea0e29c6a65f62b99998953.py", line 5, in 
    r2=random.randint('a', 'z')
  File "/usr/lib/python3.5/random.py", line 218, in randint
    return self.randrange(a, b+1)
TypeError: Can't convert 'int' object to str implicitly

Applications : The randint() function can be used to simulate a lucky draw situation. Let’s say User has participated in a lucky draw competition. The user gets three chances to guess the number between 1 and 10. If guess is correct user wins, else loses the competition. 

Python3




# importing randint function
# from random module
from random import randint
 
# Function which generates a new
# random number everytime it executes
def generator():
    return randint(1, 10)
     
# Function takes user input and returns
# true or false depending whether the
# user wins the lucky draw!
def rand_guess():
 
    # calls generator() which returns a
    # random integer between 1 and 10
    random_number = generator()
     
    # defining the number of
    # guesses the user gets
    guess_left = 3
 
    # Setting a flag variable to check
    # the win-condition for user
    flag = 0
 
    # looping the number of times
    # the user gets chances
    while guess_left > 0:
 
        # Taking a input from the user
        guess = int(input("Pick your number to "
                    "enter the lucky draw\n"))
 
        # checking whether user's guess
        # matches the generated win-condition
        if guess == random_number:
 
            # setting flag as 1 if user guesses
            # correctly and then loop is broken
            flag = 1
            break
         
        else:
             
            # If user's choice doesn't match
            # win-condition then it is printed
            print("Wrong Guess!!")
 
        # Decrementing number of
        # guesses left by 1
        guess_left -= 1
 
    # If win-condition is satisfied then,
    # the function rand_guess returns True
    if flag is 1:
        return True
 
    # Else the function returns False
    else:
        return False
 
# Driver code
if __name__ == '__main__':
    if rand_guess() is True:
        print("Congrats!! You Win.")
    else :
        print("Sorry, You Lost!")


Output

Pick your number to enter the lucky draw
8
Wrong Guess!!
Pick your number to enter the lucky draw
9
Wrong Guess!!
Pick your number to enter the lucky draw
0
Congrats!! You Win.



Previous Article
Next Article

Similar Reads

Random sampling in numpy | randint() function
numpy.random.randint() is one of the function for doing random sampling in numpy. It returns an array of specified shape and fills it with random integers from low (inclusive) to high (exclusive), i.e. in the interval [low, high). Syntax : numpy.random.randint(low, high=None, size=None, dtype='l') Parameters : low : [int] Lowest (signed) integer to
2 min read
Python - Call function from another function
Prerequisite: Functions in Python In Python, any written function can be called by another function. Note that this could be the most elegant way of breaking a problem into chunks of small problems. In this article, we will learn how can we call a defined function from another function with the help of multiple examples. What is Calling a Function
4 min read
Wand function() function in Python
function() function is similar to evaluate function. In function() function pixel channels can be manipulated by applies a multi-argument function to pixel channels. Following are the list of FUNCTION_TYPES in Wand: 'undefined''arcsin''arctan''polynomial''sinusoid' Syntax : wand.image.function(function, arguments, channel) Parameters : ParameterInp
1 min read
Returning a function from a function - Python
Functions in Python are first-class objects. First-class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures. Properties of first-class functions: A function is an instance of the Object type.You can store the function in a variable.You can pass the functi
3 min read
Accessing Python Function Variable Outside the Function
In Python, variables defined within a function have local scope by default. But to Access function variables outside the function usually requires the use of the global keyword, but can we do it without using Global. In this article, we will see how to access a function variable outside the function without using "Global". Accessing Function Variab
3 min read
Python math.sqrt() function | Find Square Root in Python
sqrt() function returns square root of any number. It is an inbuilt function in Python programming language. In this article, we will learn more about the Python Program to Find the Square Root. sqrt() Function We can calculate square root in Python using the sqrt() function from the math module. In this example, we are calculating the square root
3 min read
wxPython - GetField() function function in wx.StatusBar
In this article we are going to learn about GetField() function associated to the wx.GetField() class of wxPython. GetField() function Returns the wx.StatusBarPane representing the n-th field. Only one parameter is required, that is, field number in status bar. Syntax: wx.StatusBar.GetField(self, n) Parameters: Parameter Input Type Description n in
1 min read
How to write an empty function in Python - pass statement?
In C/C++ and Java, we can write empty function as following // An empty function in C/C++/Java void fun() { } In Python, if we write something like following in Python, it would produce compiler error. # Incorrect empty function in Python def fun(): Output : IndentationError: expected an indented block In Python, to write empty functions, we use pa
1 min read
Ways to sort list of dictionaries by values in Python - Using lambda function
In this article, we will cover how to sort a dictionary by value in Python. Sorting has always been a useful utility in day-to-day programming. Dictionary in Python is widely used in many applications ranging from competitive domain to developer domain(e.g. handling JSON data). Having the knowledge to sort dictionaries according to their values can
2 min read
Python Numbers | choice() function
choice() is an inbuilt function in Python programming language that returns a random item from a list, tuple, or string. Syntax: random.choice(sequence) Parameters: sequence is a mandatory parameter that can be a list, tuple, or string. Returns: The choice() returns a random item. Note:We have to import random to use choice() method. Below is the P
1 min read
Practice Tags :