How to generate random numbers in Python
In this article we will learn how to generate random numbers in Python and of course using methods of the language itself, quickly.
What’s up programmer, how are you? Let’s learn more about Python!
The easiest way to generate a random number is using the random library
In it we can import the randint, which is a method that takes two parameters and generates a random integer
Let’s see an example:
from random import randint print(randint(0,20))
Here we will have a random number from 0 to 20 as an answer
But it doesn’t end there, we can generate in other ways, such as floating points
Here’s how to generate random floats:
from random import uniform print(uniform(0, 10))
That way we will receive a float between 0 and 10 randomly
We also have the possibility of doing a ‘draw’ with Python, using the choice method of random
See how it works:
from random import choice sortear = [1,5,10,15,20] print(choice(sortear));
Here we have a list, which when used over the choice method, will return one of the items randomly, right? 😀
There are other methods within the random library, check out the documentation to check all the possibilities of randomness in Python
In this article we leasrned how to generate random numbers in Python
Not only integers, but also floats with the help of two methods: randint and uniform
In addition, we learned how to execute a basic draw with Python
Do you want to learn more about Python? Click here!