Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
148 views

How To Generate Random Numbers in Python Programming Language

The document discusses various ways to generate random numbers in Python programming language. It covers: 1) Generating random integers and floats using the random module's random(), randint(), and randrange() functions. 2) Randomly selecting an item from a list using random.choice(). 3) Generating random numbers with a specific length or that are multiples of a given number using randrange() and arithmetic.

Uploaded by

aorneo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

How To Generate Random Numbers in Python Programming Language

The document discusses various ways to generate random numbers in Python programming language. It covers: 1) Generating random integers and floats using the random module's random(), randint(), and randrange() functions. 2) Randomly selecting an item from a list using random.choice(). 3) Generating random numbers with a specific length or that are multiples of a given number using randrange() and arithmetic.

Uploaded by

aorneo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

How to generate random numbers in python programming language 13/4/20 10:41

Home Privacy Policy Terms and conditions Disclaimer About us Contact us ! " # $

Home Programming Language ( Data Structures ( Numerical Methods Algorithm )

Home ' Python Programming ' How to generate random numbers in python programming language

How to generate random numbers in python


programming language
 Crazy Programmer & November 22, 2019

Hello guys, what's up? Welcome to our Programiz tutorial in python programming language.
Today I am going to teach you about how to generate random numbers in python programming
language. Just like other object oriented programming (OOP) language, we can generate random
numbers in python programming language. Generating random number in python is a basic
program for python programmer. If you don’t know how to generate random numbers in python,
you cannot claim yourself as a python programmer. In machine learning algorithm randomness is
an important part of the configuration & evaluation. In machine learning we need to
' Split data into random train and test sets
' Random shuffling of a training dataset in stochastic gradient descent
' Random initialization of weights in an artificial neural network
Goals of this tutorial: –

Today we will show you various ways of generating a random number in Python programming language. In this

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 1 de 14
How to generate random numbers in python programming language 13/4/20 10:41

tutorial in python programming language, we will cover the following topics


' Generate random numbers of integer and floats number.
' Select an item randomly from a List
' Generating a random number with the specific length
' Generate a random number which is multiple of n
' Generating a random number in python, which are cryptographically secure by using
secrets module. We can also learn how to securely generate random numbers in python
programming language, security keys, and URL
' Get and Set the state in python programming language
' n-dimensional array random number generation
' Generate random numbers from a list or string
' Generate random numbers by Sampling & choose elements from population.
' Shuffle the sequence of data.
' Generate random strings and password.
' Generate random arrays, we will use use numpy.random module
' Generate random unique IDs, we will use UUID module
'
Some python module function And many more things

Random module in Python programming language

By using random module, we can generate random numbers in python programming language. To do this we
need to import random module. Let’s see it in code: ---

Code
import random
print
print("Printing random number using random.random()")
print
print(random.random())

Output:

Code
Printing random number using random.random()
0.5015127958234789

Function random() is used for generating a random number between 0 and 1 [0, 0.1 .. 1].
Generate Random Numbers by using randrang() function

To generate random integers in python programming language, we have to use randint () or


randrange() function. Below example will generate a random number in between 0 and 9.

Code
from random import randint
print
print("Printing random integer ", randint(0, 9))
print
print("Printing random integer ", randrange(0, 10, 2))

Output:

Code
Printing random integer 2
Printing random integer 6

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 2 de 14
How to generate random numbers in python programming language 13/4/20 10:41

Randomly select an item from a List


Assume, we have the following cities list. And we want to retrieve an item randomly from the list. Let’s see
how we can do this: ---

Code
import random
city_list = ['New York', 'Los Angeles', 'Chicago', 'Houston', 'Philadelphia'
print
print("Select random element from list - ", random.choice(city_list))

Output:

Code
Select random element from the list - Chicago

Generate a random number in between 1 and 100.

Below code will generate a random number in between 1 and 100.

Code
import random
for x in range
range(10):
print random.randint(1,101)

x in range(10), determines how many random values we want to print. If we want to print 20
numbers, we can set just simply 20 in 2nd line. random.randint(1,101) will select random integer
values in between 1 and 100. So, we can say that, above code will print 10 random values of
numbers between 1 and 100.
random.randrange() function in python programming language
In python programming language random.randrange() function is used for generating random number in a
given range. For example, if we want to generate random numbers in between 20 to 60, then we can use this
function.
How to use random.randrange()

Syntax:

Code
random.randrange(start, stop[, step])

Above we can see that random.randrange() function takes 3 parameters. But, here two parameters (start and
step) are optional
'randrange(): is exclusive function. For example, randrange (10,20,1). It will never select
20. It will only return random number from 10 to 19
' Start: starting number in a range. We can say it, lower limit. If we will not specified, by
default it assume starts is 0
' Stop: last number in a range. We can also say it, upper limit.
' Step: difference between each number. It is optional parameters. If we will not specified, by

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 3 de 14
How to generate random numbers in python programming language 13/4/20 10:41

default it assume step value is 0


'We can only use integer value parameters in random.randrange() function. Otherwise it
will throw an ValueError.
' If stop <= start or step =0, it will also throw an ValueError.
Example:

By using random.randrange() function we can print a random number in a given range.

Code
import random

print
print("Generate random integer number within a given range in Python ")
#random.randrange() with only one argument
print
print("Random number between 0 and 10 : ", random.randrange(10))

#random.randrange() with two arguments


print
print("Random number between 20 and 40 : ", random.randrange(20, 40))

#random.randrange() with three argument


print
print("Random number between 0 and 60 : ", random.randrange(0, 60, 6))

Output:

Code
Generate random integer number within a given range in Python
Random number between 0 and 10 : 7
Random number between 20 and 40 : 32
Random number between 0 and 60 : 48

Generate the random number with the specific length


What if, if you need to generate a random number of length n. For example, if we want to generate random
number which length are 4. We can generate a random number of certain length by using function
random.randrange(). Let’s see some example: ---

Code
import random

number = random.randrange(1000, 9999)


print
print("First random number of length 4 is ", number)

number = random.randrange(1000, 9999)


print
print("Second random number of length 4 is ", number)

Output:

Code
First random number of length 4 is 1931
Second random number of length 4 is 5715

Generate a random number of multiple of n


What if, if you need to print random integer values & those are in between 1 and 100 but values are multiple of
5? You have to use a little more arithmetic so that the random integer is in fact a multiple of five, then

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 4 de 14
How to generate random numbers in python programming language 13/4/20 10:41

everything are same as before we have learned. Let’s check this in our below code:---

Code
import random

number = random.randrange(10, 100, 10)


print
print("using randrange First random number multiple of 10 is ", number)

number = random.randrange(10, 100, 10)


print
print("Using randrange Second First random number multiple of 10 is ", number

When above code will execute, our output looks like below−

Code
using randrange First random number multiple of 10 is 70
Using randrange Second First random number multiple of 10 is 30

Generate 10 random numbers in between 1 to 100

Code
import random

print
print(random.sample(range
range(1, 101), 10))

After executing the above code our output will be shown as a list:

Code
[11, 72, 64, 65, 16, 94, 29, 79, 76, 27]

Random number between 1 and 10

If we want to generate random floating point number in between 1 and 10, then we can use
uniform() function

Code
from random import *

print
print(uniform(1, 10))

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 5 de 14
How to generate random numbers in python programming language 13/4/20 10:41

random.uniform(start, end) in python programming language


'To generate a floating point number within a given range, we can use
random.uniform()function.
'For example, we want to generate random float number in between 10.5 to 25.5. In the result
we can get output which is less than 25.5. We never get 25.5.
Example: –

Code
import random
print
print("floating point within given range")
print
print(random.uniform(10.5, 25.5))

Output:

Code
floating point within given range
16.76682097326141

random.triangular(low, high, mode) in python programming


To use 3 number in a simulation for generating a random number in python programming language, we can use
random.triangular() function. In this function by default lower limit/low is zero and the upper limit/high value
is 1. This function return a random float value (n), where low <= n <= high and the mode is between those
bounds.

Example:

Code
import random
print
print("floating point triangular")
print
print(random.triangular(10.5, 25.5, 5.5))

Output:

Code
floating point triangular
16.114862085401924

Cryptographically secure random generator in Python


If we want to generate cryptographically secure random number in python programming language we need to
use a function. Do to this we have to use random.SystemRandom().random() instead of random. random().
If we generate random number by random.SystemRandom().random() function, then our output will be
secure.
To secure the random generator in Python programming language, we have to use the following approaches.
' To secure random data need to import secrets module
' Have to use random.SystemRandom class
Example:

Code
import random
import secrets

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 6 de 14
How to generate random numbers in python programming language 13/4/20 10:41

number = random.SystemRandom().random()
print
print("secure number is ", number)

print
print("Secure byte token", secrets.token_bytes(16))

Output:

Code
secure number is 0.11139538267693572

Secure byte token b'\xae\xa0\x91*.\xb6\xa1\x05=\xf7+>\r;Y\xc3'

Get and Set the state of python random Generator


In python programming language, it has two 2 functions. Those are random.getstate() and
random.setstate(state). This 2 function help us to capture the current internal state of the random numbers. We
can generate sequence of data by using this module. In random.setstate(state), you cannot change the sate
value, if you want to get previous state. Because by changing the state value, you are altering the state.

To have a clear understanding let’s see an example: ---

Code
import random

number_list = [3, 6, 9, 12, 15, 18, 21, 24, 27, 30]

print
print("First Sample is ", random.sample(number_list,k=5))

state = random.getstate() # store this current state in state object


print
print("Second Sample is ", random.sample(number_list,k=5))

random.setstate(state) # restore state now using setstate


print
print("Third Sample is ", random.sample(number_list,k=5)) #Now it will print the same
#second sample list

random.setstate(state) # restore state now


print
print("Fourth Sample is ", random.sample(number_list,k=5)) #again it will print the
#same second sample list again

Output:

Code
First Sample is [18, 15, 30, 9, 6]
Second Sample is [27, 15, 12, 9, 6]
Third Sample is [27, 15, 12, 9, 6]
Fourth Sample is [27, 15, 12, 9, 6]

Look at above code. By setting the random generator, we are getting same sample list
Generate a random n-dimensional array of float numbers
Whenever we want to generate an array of random numbers in numpy python programming
language, we need to use numpy.random package.

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 7 de 14
How to generate random numbers in python programming language 13/4/20 10:41

' numpy.random.rand():generate n-dimensional array of random floating point numbers in


the range of [0.0, 1.0)
' numpy.random.uniform: generate n-dimensional array of random floating point numbers in
the range of [low, high)

Code
import numpy
random_float_array = numpy.random.rand(2, 2)
print
print("2 X 2 random float array in [0.0, 1.0] \n", random_float_array,"\n"

random_float_array = numpy.random.uniform(25.5, 99.5, size=(3, 2))


print
print("3 X 2 random float array in range [25.5, 99.5] \n", random_float_array

Output:

Code
random float array in [0.0, 1.0]
[[0.99158699 0.02109459]
[0.41824566 0.66862725]]

random float array in [25.5, 99.5]


[[93.061888 86.81456246]
[76.19239634 50.39694693]
[82.25922559 78.63936106]]

Generate random numbers of multidimensional array of integers numbers

In python programming language, Nuumpy module has a numpy.random package, which can generate random
numbers array. To generate random multidimensional array, we need to use the following Numpy methods.
' randint() // generate integer random number
' random_integers()// generate integer random number
'np.randint(low[, high, size, dtype]) // generate random integers array from low (inclusive) to
high (exclusive).
'np.random_integers(low[, high, size]) // generate Random integers array of type numpy int
between low and high, inclusive.
Now, let see the examples.

Generate multidimensional array integers:

Following code generate 4 x 4 dimensional arrays of integers in between 10 and 50, where 10 & 50 are
exclusive

Code
import numpy
print
print("4 x 4 array of ints between 10 and 20 inclusive")
newArray = numpy.random.randint(10, 50, size=(4, 4))
print
print(newArray)

Output:

Code
[[10 48 30 24]
[13 46 30 11]
[12 28 49 26]

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 8 de 14
How to generate random numbers in python programming language 13/4/20 10:41

[30 18 49 35]]

Generate a 5 x 3 array of ints between 60 and 100, inclusive:

Following code generate 5 x 3 dimensional arrays of ints in between 60 and 100, where 60 and 100 are
inclusive

Code
import numpy
print
print("3 x 5 array of ints between 10 and 20 exclusive")
newArray = numpy.random.random_integers(60, 100, size=(3, 5))
print
print(newArray)

Output:

Code
[[63 76 95 93 75]
[71 84 63 99 93]
[65 64 66 69 92]]

Generate random number from a list or string


random.choice()
To pick a random element from the sequence, we can use random.choice(seq) method. random.choice(seq)
returns a single item/number from the list or string.

Example:

Code
list = [55, 66, 77, 88, 99]
print
print("random.choice to select a random element from a list - ", random.choice

Output:

Code
random.choice to select a random element from a list
77

When we have to randomly choose more than one element from the sequence, there we can use
random.choices(population, weights=None, *, cum_weights=None, k=1) method

Example: –

Code
import random

#sampling with replacement


list = [20, 30, 40, 50 ,60, 70, 80, 90]
sampling = random.choices(list
list, k=5)
print
print("sampling with choices method ", sampling)

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 9 de 14
How to generate random numbers in python programming language 13/4/20 10:41

Output:

Code
sampling with choices method [90, 50, 40, 60, 40]

random.sample()
When we have to randomly choose more than one element from the sequence, there we can also
use random.sample(population, k) method. From the population, this method returns a list of
unique items. Here k is the number of return elements.

Example: –

Code
import random
list = [2,5,8,9,12]
print ("random.sample() ",random.sample(list
list,3))

Output:

Code
random.sample() [2, 9, 5]

random.shuffle(x[, random])
If we want to shuffle or randomize a list or string sequence, there we can use random.shuffle() function.
Shuffle card game is a common example of this.

Example:

Code
list = [2,5,8,9,12]
random.shuffle(list
list)
print ("Printing shuffled list ", list
list)

Output:

Code
Printing shuffled list [5, 9, 12, 2, 8]

Generate random number from an array


To generate random number from an array, there we can use numpy.random.choice() function.
We can also use it to get single or multiple random numbers from the n-dimensional array

Example:

Code
import numpy

array =[10, 20, 30, 40, 50, 20, 40]

single_random_choice = numpy.random.choice(array, size=1)


print
print("single random choice from 1-D array", single_random_choice) Find us in Social M

multiple_random_choice = numpy.random.choice(array, size=3, replace=False)


# LinkedIn
print
print("multiple random choice from 1-D array without replacement ",

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 10 de 14
How to generate random numbers in python programming language 13/4/20 10:41

multiple_random_choice)

! Facebook
multiple_random_choice = numpy.random.choice(array, size=3, replace=True)
print
print("multiple random choice from 1-D array with replacement ", multiple_random_choice
Pages

Home
Terms and conditions
Output: Contact Us

Code
Popular Posts
single random choice from 1-D array [10]
multiple random choices from the 1-D array without replacement [20 20 10]
Cheat she
multiple random choices from the 1-D array with replacement [10 50 50] programm
& November
Generate random UUIDs
UUID means Universally Unique IDentiPer. In python programming language, it provides immutable Generate a
UUID objects. To do this we have to use uuid.uuid4() function. This function can generate 128 bit long numbers i
random unique ID. UUIDs object is cryptographically safe. programm
& November

Example:
Linked lis
insert, del
Code
Programm
import uuid & November

# get a random UUID


safeId = uuid.uuid4() Follow b
print
print("safe unique id is ", safeId)
Get all latest conten
to your

Output:
Email A

Code
safe unique id is UUID('78mo4506-8btg-345b-52kn-8c7fraga847da')

Generating random number for a Dice Game


I have created a simple dice game to understand random module functions. In this game, we have two players Data Structures
and two dice. To understand random numbers in python, below I will show you a dice game example.
Stack prog
Rules of the dice game: Push,Pop,
' Each player shuffle both the dice and play one by one. in C Progr
& November
' Sum the two dice number and adds it to each player’s scoreboard.
' The Player will be the winner, who scores high number Heap prog
Reheap do
Code
Programm
import random & November

Queue pro
PlayerOne = "Eric"
dequeue, f
PlayerTwo = "Kelly" C Program
& November

EricScore = 0
Linked lis
KellyScore = 0 insert, del
Programm
& November
# each dice contains six numbers
diceOne = [1, 2, 3, 4, 5, 6] C++ Progr
Binary Sea

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 11 de 14
How to generate random numbers in python programming language 13/4/20 10:41

Binary Sea
diceTwo = [1, 2, 3, 4, 5, 6]
Lists
& November
def playDiceGame():
"""#Both Eric and Kelly will roll both the dices using shuffle method"""

C++ Progr
for i in range
range(5): Expressio
#shuffle both the dice 5 times & November

random.shuffle(diceOne)
C++ Progr
random.shuffle(diceTwo)
Heap
firstNumber = random.choice(diceOne) # use choice method to pick one number randomly & November
SecondNumber = random.choice(diceTwo)
return firstNumber + SecondNumber Linked Lis
using C++
& November
print
print("Dice game using a random module\n")

#Let's play Dice game three times Categories


for i in range
range(3):
# let's do toss to determine who has the right to play first Algorithm C Plus Plus
EricTossNumber = random.randint(1, 100) # generate random number from 1 to 100.
C Programming
#including 100
Database Java Progra
KellyTossNumber = random.randrange(1, 101, 1) # generate random number from 1 to
#100. dosen't including 101 Numerical Methods

R programming
if
if( EricTossNumber > KellyTossNumber):
print
print("Eric won the toss")
EricScore = playDiceGame()
KellyScore = playDiceGame()
else
else:
print
print("Kelly won the toss")
KellyScore = playDiceGame()
EricScore = playDiceGame()

if
if(EricScore > KellyScore):
print ("Eric is winner of dice game. Eric's Score is:", EricScore,
"Kelly's score is:", KellyScore, "\n")
else
else:
print
print("Kelly is winner of dice game. Kelly's Score is:", KellyScore
"Eric's score is:", EricScore, "\n")

Output:

Code
Dice game using a random module

Kelly won the toss


Eric is the winner of a dice game. Eric's Score is: 9 Kelly's score is
is: 6

Kelly won the toss


Eric is the winner of a dice game. Eric's Score is: 11 Kelly's score is
is: 9

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 12 de 14
How to generate random numbers in python programming language 13/4/20 10:41

Eric won the toss


Kelly is the winner of a dice game. Kelly's Score is: 12 Eric's score is
is:

Today we have learned many things about python programming language. I hope you guys have
understood everything which I have discussed earlier. . So, guys, that’s about how to generate
random numbers in python programming language. Later I will discuss another tutorial on
python programming language. Till then, take care. Happy Coding

Tags: Python Programming

! Facebook " Twitter * Google+ $ # + ,

. OLDER NEWER -
1 to 100 random number generator in python Generate a list of random numbers in python
programming language programming language

You may like these posts

Cheat sheet for python Generate a list of random How to generate random
programming language numbers in python numbers in python
& November 27, 2019 programming language programming language
& November 23, 2019 & November 22, 2019

Post a Comment

0 Comments

Enter your comment...

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 13 de 14
How to generate random numbers in python programming language 13/4/20 10:41

Most Recent Random Posts Message us !

Cheat sheet for python Generate a list of random


programming language numbers in python
Most Popular
& November 27, 2019 programming language
& November 23, 2019
Cheat sheet for python
Generate a list of random
How to generate random programming language
numbers in python
numbers in python & November 27, 2019
programming language
programming language
& November 23, 2019
& November 22, 2019
Generate a list of random
How to generate random numbers in python
1 to 100 random number
numbers in python programming language
generator in python
programming language & November 23, 2019
programming language
& November 22, 2019
& November 20, 2019
Linked list program to create,
insert, delete & search using C
Programming
& November 30, 2018

Created By / by TemplatesYard | Distributed by programiz.xyz Home About Contact Us

https://www.programiz.xyz/how-to-generate-random-numbers-in Página 14 de 14

You might also like