Random
In programing, you will sometimes need to select a random number or a random item in a list.
To be able to do that, we will need to import a module called random
. It is very easy to import a module in Python, all you have to do is write at the very top of your code:
Based on what you want to do, you will need to use a different function from the module random:
To randomly select an integer, you can use the randint function.
The randint function will randomly select an integer between two parameters that you give.
For example, if you want to select a random integer between 3 and 7, included, you can write:
To randomly select a float, you can use the uniform function.
The uniform function will randomly select a float between two values that you give.
For example, if you want to select a random float between 3 and 7, included, you can write:
To randomly select an item from a sequence, you can use the choice function.
The choice function will randomly select an item from a given sequence.
For example, if you want to select a random item from the list ["chocolate", "vanilla", "strawberry"], you can write: