How to Generate a Random Number in Python with Examples

Spread the love

In this program, you will learn how to write python code for random numbers.  you have to import random library to generate random numbers. Then you need to call random.randint function with starting number and ending number.

It will produce the random number from with in the range.

The random number are change for each execution. you can define random.seed(123) to stable the random values.

How to generate random numbers from 0 to 1

import random #random.seed(123) a=random.randint(0,1) print(a)

Output:

1

How to generate random numbers from 0 to 10:

import random #random.seed(123) a=random.randint(0,10) print(a)

Output:

7

How to generate random numbers from 0 to 100

import random #random.seed(123) a=random.randint(0,100) print(a)

Output:

71

If you need random matrix number for data science operations, you need import numpy library. By using numpy, you can define random numbers with mu

import numpy as np a=np.random.randint(2,size=10) print(a) # 2 dimensional array a=np.random.randint(10,size=(2,5)) print(a) # 3 dimensional array a=np.random.randint(10,size=(3,5)) print(a)

Output:

[0 1 1 0 1 0 0 1 0 1]
[[1 9 0 8 9]
[2 7 9 1 7]]
[[5 2 6 3 0]
[5 2 0 5 9]
[2 1 1 1 5]]

 

admin

admin

Leave a Reply

Your email address will not be published. Required fields are marked *