In Python programming, you can generate a random integer, doubles, longs etc . in various ranges by importing a "random" class.
In Python, we can generate a random integer, doubles, long, etc in various ranges by importing a "random" module. In the following example, we will learn how to generate random numbers using the random module.
Syntax:
First, we have to import the random module and then apply the syntax:
import random
Generating a Random Number
The random module provides a random() method which generates a float number between 0 and 1.
Output:
If we run the code again, we will get the different output as follows.
Generating a Number within a Given Range
Python random module provides the randint() method that generates an integer number within a specific range. We can pass the two numbers as arguments that defines the range. Let's understand the following example.
Example - 1:
Output:
Example - 2:
Output:
Using for loop
The randint() method can be used with for loop to generated a list of random numbers. To do so, we need to create an empty list, and then append the random numbers generated to the empty list one by one. Let's understand the following example.
Example -
Output:
Using random.sample()
The random module also provides the sample() method, which directly generates a list of random numbers. Below is the example of generating random numbers using the sample() method.
Example -
Output:
In the above code, we have used the range() function, which generates the numbers between the given range.
need an explanation for this answer? contact us directly to get an explanation for this answer