Python is a popular programming language when working with math and data because of how easy it is to work with numbers.
A popular operation in Python is to generate random numbers in a specific range so that you can use it in your code.
In this post, we'll learn how to generate random numbers in a specific range in Python.
Using random.randint()
A simple way to generate random numbers in a specific range is to use the randint() function.
This function comes from the random module and you can use it by just importing it.
Let's look at how to generate a random number between 0 and 10 in Python:
PYTHONimport random
number = random.randint(0, 10)
print(number)
BASH5
Keep in mind that this will include the number 0 but exclude the number 10.
Now, if you want to generate a list of these numbers, you can use the range() function:
PYTHONimport random
numbers = [random.randint(0, 10) for p in range(0, 10)]
print(numbers)
BASH[1, 8, 4, 0, 5, 9, 2, 3, 6, 8]
Here is the general syntax:
PYTHONimport random
range_start = 0
range_end = 10
gen_count = 10
numbers = [random.randint(range_start, range_end) for p in range(0, gen_count)]
print(numbers)
Using random.randrange()
Another function that comes with the random module is randrange().
This function also requires a start and end range, however, it also allows you to specify a step size.
The step parameter is optional, but if you don't specify it, it will default to 1.
This parameter controls the step size of the range, so if you want to generate a list of numbers between 0 and 10, but only in steps of 2, you can use the following syntax:
PYTHONimport random
numbers = [random.randrange(0, 10, 2) for p in range(0, 10)]
print(numbers)
BASH[4, 2, 6, 2, 4, 8, 6, 4, 2, 2]
Using random.sample()
When you want to ensure that you have a random list of unique numbers, you can use the sample() function.
This function will generate a random list of integers for you while ensuring they are all unique.
Let's see how it works:
PYTHONimport random
numbers = random.sample(range(0, 10), 10)
print(numbers)
BASH[4, 3, 8, 1, 7, 2, 9, 6, 0, 5]
Conclusion
In this post, we learned how to generate random numbers in a specific range in Python.
Python has several built-in functions that you can use to generate the random numbers that you need. Simply pick the one that is right for your use-case.
Thanks for reading and happy coding!
Getting Started with TypeScript
Managing PHP Dependencies with Composer
How to Serve Static Files with Nginx and Docker
How to build a Discord bot using TypeScript
Getting Started with Sass
Using Puppeteer and Jest for End-to-End Testing
How to Scrape the Web using Node.js and Puppeteer
Getting Started with Moment.js
Creating a Twitter bot with Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with Vuex: Managing State in Vue
Setting Up a Local Web Server using Node.js
