randint() Function in Python
Last Updated :
09 Aug, 2024
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.
Python
# 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))
OutputRandom 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.
Python
import random
beg,end=1,1000
for i in range(5):
print(random.randint(beg, end))
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.
Python
# 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.
Python
# 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.
Python
# 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.
randint() Function in Python – FAQs
What Does the randint Function Do in Python?
The randint function in Python generates a random integer within a specified inclusive range. It is part of the random module and is used to return a random integer between the two arguments provided, where both endpoints are included.
What is the Difference Between the random Function and randint Function?
- Part of Python’s
random module. - Returns a random floating-point number between 0.0 to 1.0 (1.0 not included).
- It does not take any arguments.
import random
print(random.random()) # Outputs: a number like 0.37444887175646646
random() Function:Example:randint() Function:- Also part of the
random module. - Returns a random integer between the two inclusive limits provided as arguments.
- Requires two arguments: the lower and upper bounds of the range.
Example:
import random
print(random.randint(1, 10)) # Outputs: an integer like 6
What Package is randint In?
The randint function is in the random module, which is part of Python’s Standard Library. It provides functions for generating random numbers, and randint is specifically used for generating random integers.
How to Generate a Random Number from 1 to 10 in Python?
To generate a random number from 1 to 10 in Python, you can use the randint function from the random module. Here’s how you can do it:
import random
random_number = random.randint(1, 10)
print(random_number)
This code snippet will print a random integer between 1 and 10, inclusive.
What is the Use of the random() Function?
The random() function is used to generate a random float number between 0.0 and 1.0. It’s useful when you need a random decimal value within this range, and it is commonly used in simulations, games, testing, and wherever random sampling is required. Because it generates a number up to but not including 1.0, it’s particularly useful when combined with other functions or scaled to fit a desired range. For example, multiplying the result by 100 would provide a random float from 0.0 to 100.0, not inclusive of 100.
Similar Reads
Python Random Module
Python Random module generates random numbers in Python. These are pseudo-random numbers means they are not truly random. This module can be used to perform random actions such as generating random numbers, printing random a value for a list or string, etc. It is an in-built function in Python. List
7 min read
Python - random.seed( ) method
random() function is used to generate pseudo-random numbers in Python. That implies that these randomly generated numbers can be determined. random() function generates numbers for some values. This value is also called seed value. Here we will see how we can generate the same random number every ti
3 min read
random.getstate() in Python
random() module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.getstate() The getstate() method of the random module returns an object with the curr
1 min read
random.setstate() in Python
Random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.setstate() The setstate() method of the random module is used in conjugation with the g
2 min read
random.getrandbits() in Python
random module is used to generate random numbers in Python. Not actually random, rather this is used to generate pseudo-random numbers. That implies that these randomly generated numbers can be determined. random.getrandbits() The getrandbits() method of the random module is used to return an intege
1 min read
randrange() in Python
Generating a random number has always been an important application and having many uses in daily life. Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module. More to this function is dis
6 min read
randint() Function in Python
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 SyntaxSyntax: randint(st
6 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 im
1 min read
Python - random.choices() method
The choices() method returns multiple random elements from the list with replacement. Unlike random.choice(), which selects a single item, random.choices() allows us to select multiple items making it particularly useful for tasks like sampling from a population or generating random data. Example: [
3 min read
Python | random.sample() function
sample() is an built-in function of random module in Python that returns a particular length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random sampling without replacement. Syntax : random.sample(sequence, k) Parameters:sequence: Can be a list, tuple, string, or
2 min read