In this tutorial, we will learn how to create a Random Number Generator in Python. Random numbers are often used in programming for various purposes, such as generating random data, shuffling data, or running simulations.
Python provides a built-in module called random, which contains functions to generate random numbers. Let’s jump right into the steps to create a simple random number generator.
Step 1: Import the random module
First, we need to import the random module in our Python script to use the functions provided by this module. To do this, add the following line of code at the beginning of your script:
1 |
import random |
Step 2: Generate a random number
Now, we can use the randint() function from the random module to generate a random integer number. The randint() function takes two arguments: the lower and upper bounds of the desired random number. The function returns a random integer number within the given range, including both bounds.
Here’s an example of how to generate a random number between 1 and 100:
1 2 |
random_number = random.randint(1, 100) print("Random number between 1 and 100 is:", random_number) |
Step 3: Generate a random float number
If you want to generate random floating-point numbers, you can use the random() function. This function returns a floating-point number in the range [0.0, 1.0). If you want to generate numbers in a different range, you can apply basic scaling on the output.
For example, if you want a random float number between 1 and 10, you can do the following:
1 2 |
random_float_number = 1 + random.random() * 9 print("Random float number between 1 and 10 is:", random_float_number) |
Full Code
Here is the complete code for generating random integer and floating-point numbers in Python:
1 2 3 4 5 6 7 |
import random random_number = random.randint(1, 100) print("Random number between 1 and 100 is:", random_number) random_float_number = 1 + random.random() * 9 print("Random float number between 1 and 10 is:", random_float_number) |
Output
Random number between 1 and 100 is: 42 Random float number between 1 and 10 is: 6.7348082562480305
Remember that the output will change each time you run the script since it generates random numbers.
Conclusion
In this tutorial, we have learned how to make a random number generator in Python using the random module. We have seen how to generate random integer and floating-point numbers in specific ranges. You can now create your applications involving randomness with more confidence.