Python program to generate a random number
Written by
Python program to generate a random number
In python, there are a set of functions that are used to manipulate random numbers.
Random number generators are often used in games, lotteries, and other applications that require randomly generated numbers. In Python, we can use the random
module to generate random numbers using functions such as random()
, randint(a, b)
, and randrange(a, b)
. These functions allow us to generate a variety of random numbers with different properties, such as floating-point numbers, integers within a given range, and integers within a given range with a specific step size.
rd.random(), rd.randint(1,100), rd.randrange(1,100), etc.
Algorithm:
- Import the
random
module in Python. - Use the
random()
function to generate a random floating-point number between 0 and 1. - Use the
randint(a, b)
function to generate a random integer betweena
andb
(inclusive). - Use the
randrange(start, stop, step)
function to generate a random integer within a given range[start, stop)
with a specific step size. - Print the output of each function to see the resulting random numbers.
- Exit the program.
Code:
import random as rd
print(rd.random())
#gives a random float number
print(rd.randint(1,100))
#gives a random integer between these 2 numbers
print(rd.randrange(1,100))
#gives a random integer in this range
print(rd.choice([1,2,3,4,5,6,7]))
#gives a random integer in these choices
Output:
0.3583190240354166
89
57
4