Here you will find the code written in Python, PHP, and JavaScript to generate a random number.
How to Generate a random number using Python?
Python has an inbuilt package called random that you can use to generate random numbers.
import random
n = random.random()
print(n)
How to Generate a random integer between two numbers using Python?
The randint()
method of the Python random module is used to generate a random integer between two numbers.
This method takes two arguments, the first one is the minimum value and the second one is the maximum value. Both arguments must be an integer.
The following Python code is to generate a random number between 1 and 10.
from random import randint
n = randint(1, 10)
print(n)
How to generate random numbers using PHP?
In PHP, there are two in-built functions rand()
and mt_rand()
that you can use to generate a random number.
Both rand()
and mt_rand()
do the same thing, but mt_rand is faster and more accurate than the rand function.
<?php
$n = rand();
$n2 = mt_rand();
echo $n,' - ', $n2;
The PHP rand and mt_rand functions are also used to generate a random integer between two numbers.
You have to pass two arguments, one is for the min value and the other one is for the max value.
<?php
$n = rand(1, 10);
$n2 = mt_rand(50, 100);
echo $n,' - ', $n2;
7 - 60
There is one more function in PHP called lcg_value()
, this is function generate a random float value in a range between 0 and 1.
<?php
$n = lcg_value();
echo $n;
0.56877131820271
How to generate random numbers using JavaScript?
The JavaScript Math.random()
method is used to generate a random float value in a range between 0 and 1.
const n = Math.random()
console.log(n)
0.7616250771931148
Currently there is no built-in function in JavaScript to generate a random number between two numbers. But there is a trick to achieve this.
The trick is – You have to use two math methods together – Math.random()
and Math.floor()
The following randInt()
function generates a random integer between two numbers.
const randInt = (min, max) => {
return Math.floor(Math.random() * (max - min + 1) + min);
};
for (let i = 0; i < 10; i++) console.log(randInt(25, 49));
37
41
45
36
34
46
25
43
27
46
JS random number between 0 to 10
Math.floor(Math.random() * (10 + 1))
JS random number between 1 to 10
Math.floor((Math.random() * 10) + 1)