Python has huge collection of modules in which Random is one of it. Python Random module is used to generate random numbers. There are several functions under random module. To use random module we need to import that module using import random. This module is very useful to create a simple games which requires random numbers.
Python random Module
The random module in Python provides a set of functions for generating random numbers and performing randomization operations. It’s commonly used for tasks like generating random data, shuffling sequences, and simulating random events.
Let’s discuss some key functions provided by random module:
Seed
Shuffle
random.random()
Randrange
Randint
SEED
Seed is used to fix the random number that to be generated. It generates same random number even if you execute it multiple times . Mainly used to encrypting key.
If you use seed then output of random function will be same even after several executions. Observe the difference between 3rd print statement and remaining statements.
import random
#Statement with seed
random.seed(3)
print(random.random())
random.seed(3)
print(random.random())
#statement without seed
print(random.random())
random.seed(3)
print(random.random())
randrange function in random module generates a random value in given range
Syntax: random.randrange(start,stop,incrementer) start- starting point of range (inclusive) stop- ending point of range (exclusive) incrementer- optional parameter which is defaultly 1. first print statement prints random number from 10 to 19 second print statement prints random number from 1 to 9 and here increment value is 2 so it generates only odd random values.
import random
n=int(input("Guess a number between 1 to 10 : "))
x=random.randint(1,10)
print("Computer generated number :",x)
print("Your guessed number :",n)
if(n==x):
print("You guessed it right :)")
else:
print("Wrong guess , Try again ")
Output 1:
Guess a number between 1 to 10 : 5 Computer generated number : 1 Your guessed number : 5 Wrong guess , Try again
Output 2:
Guess a number between 1 to 10 : 4 Computer generated number : 4 Your guessed number : 4 You guessed it right :)
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Login/Signup to comment