Random number Generation in Python
It can be implemented by many methods based on user requirements.Based on the fucntions,the list is given below.
- ‘randint()’
- ‘random()’ or ‘uniform()’
- ‘choice()’
- ‘sample()’
- ‘shuffle()’
- ‘seed()’
- ‘secrets.randbelow()’
- ‘rand()’
- Various types of Distrbutions
1. ‘randint()’:
This
function is a built-in function of random package. It reads the number limit to
generate random values.
Code:
# This code imports random package
import random
print("The random value is:")
#prints the random integer value in the range 1 to 100.
print(random.randint(1, 100))
Output:
The random value is:
11
2.‘random()’ or ‘uniform()’:
This
generates random float number. ‘random()’ gives a single float number. ‘uniform()’
gives you the float number within the range.
Code:
import random
print("The random value generated by random():")
print(random.random())
print("The random number generated in the number limit
1.1 to 99.9")
print(random.uniform(1.1, 99.9))
Output:
The random value generated by random():
0.9317870646028138
The random number generated in the number limit 1.1 to 99.9
65.10704409480574
3. ‘choice()’
This
code generates the random choice from the list given.
Code:
import random
#Create a list of elements
vehicle_list = ['car', 'bus', 'lorry','auto','van','bike']
print("A random choice from the vehicle list generated
by system:")
#print the random choice
print(random.choice(vehicle_list))
Output:
A random choice from the vehicle list generated by system:
bus
4.’sample()’:
This code
uses sample() function. It sets the range as 75. The number of elements to
print is 6.
Code:
import random
print("The random numbers generated with a range:")
print(random.sample(range(1, 75), 6))
Output:
The random numbers generated with a range:
[71, 53, 38, 31, 29, 36]
5.’shuffle()”:
This
function shuffles the card values randomly.
Code:
import random
p_cards = [1,2,3,4,5,6,7,8,9,10]
print("The original cards are:")
print(p_cards)
random.shuffle(p_cards)
print("The shuffled cards are:")
print(p_cards)
Output:
The original cards are:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
The shuffled cards are:
[5, 2, 10, 6, 4, 7, 8, 1, 9, 3]
These are the basic random number, character generation python
codes. Hope, this coding is useful to you. Next part covers advanced methods. Keep
Coding!!!!
Comments
Post a Comment