How to make a random number in Python
Generate random numbers in Python with an example: Learn how to create a random number in Python using the random module and a simple function.
Generating a Random Number in Python
Generating a random number in Python is quite simple. The following example demonstrates how to generate a random number between 0 and 1000.
import random
# Generate a random number between 0 and 1000
x = random.randint(0, 1000)
print(x)
The random.randint()
function takes two arguments: a lower and an upper bound. It produces a random number between the two bounds. In this example, the random number is generated between 0 and 1000. The generated random number is then stored in the x
variable and printed out.
However, there are times when you may want to produce a random number with more precision. For this, you can use the random.random()
function. This function takes no arguments and produces a random number between 0 and 1. The following example shows how to generate a random number between 0 and 1000 with more precision.
import random
# Generate a random number between 0 and 1000
x = random.random() * 1000
print(x)
The random.random()
function produces a random number between 0 and 1, and this number is then multiplied by 1000 to produce a random number between 0 and 1000. The generated random number is then stored in the x
variable and printed out.
In conclusion, generating a random number in Python is quite simple. You can use either the random.randint()
or the random.random()
function to generate a random number between 0 and 1000.