Python provides different functions to generate random numbers, defined in random Standard library.
- The
randint()function:- Syntax:
random.randint(x, y) - It return a random integer between specified range
[x, y], inclusive of both x and y; i.ex <= n <= y. Herenis the number returned byrandint(x, y)function.
- Syntax:
- The
random()function:- Syntax:
random.random() - The
random()function doesnโt accept any arguments. - It return a random floating point value between
[0.0, 1.0)range.
- Syntax:
In this article weโll see how to how to generate random number in Python programming language. Let us understand also with an example.
Example for generating integer number with randint() function
Passing the variable as an argument, and then comparing the result to the int class.
import random
print(random.randint(1, 100))
# 24
Example for generating floating point number with random() function
import random
print(random.random())
# 0.7021509552090657
Note that we may get different output because this program generates random number.
Hope you like this!
Keep helping and happy ๐ coding
Related Articles
Deepen your understanding with these curated continuations.
How to Display Multiplication Tables in Python
Learn to generate multiplication tables in Python using for loops and the range() function. A perfect exercise for beginners to master iterative logic.
How to Check if a Variable is an Integer in Python
Learn how to check if a variable is an integer in Python using the type() and isinstance() functions. Essential for data validation and type-safe coding.
Swapping Variable Values in Python
Discover multiple ways to swap the values of two variables in Python, including the elegant tuple unpacking method and the traditional third-variable approach.