How to Generate a Random Number in Python 


               


How to Generate a Random Number in Python



Python


In this article, we show how to generate a random number in Python.

To generate a random number in Python, we must import the random module.

Once we have this random module imported, we can generate random floats or integers in any interval that we want.


How to Generate Random Floats

To generate a random float number between 0 and 1, you can use the line, random.random(), in order to do so



Using the line above will yield a number between 0 and 1.

If you want a random float between a certain range, then you would multiply random.random() by the range that you want.

For example, if you want to generate a random float between 0 and 10, then you would multiply random.random() by 10.

So, the code would be that which is shown below.



So, this code above will now generate a random float between 0 and 10.

If you want to generate a random float between 0 and 100, then you would multiply random.random() by 100.


How to Generate a Random Integer

To generate a random integer in Python, you would use the line random.randint() function. Inside of the parameter of the randint() function, you would put the range that you want returned.

For example, if you want to generate a random integer between 1 and 10, the statement would be, random.randint(1,10).

This is shown in the code below.



So, the code above will return a random integer between 1 and 10.

If you wanted to generate a random integer between 1 and 100, the code would be, random.randint(1,100).

And this is how random numbers can be generated in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...