In this tutorial you will learn about python random which is an in-built module used for generating random number in python.
Python module random have set of function which is used for generating or manipulating random number.
This particular type of function in python is used in multiple games like lotteries or any other application.
Example: Python random()
>>> import random
>>> random.random()
0.456723456
In the above example we have import random module and then used random function which is inside of random module.
The random function generate the output between 0.0 to 1.0 which is in the form of float number.
Methods of random module
choice()
It is used to Return a random element from the given sequence.
random()
It is used to returns a random float number between 0 and 1.
randint()
It is used for returning a random number between the given range
shuffle()
It takes a sequence and returns it into random order.
seed()
it is used for initialization the random number generator.
sample()
It is used to returns a given sample of a sequence
getstate()
It returns the current internal state of the random number generator
setstate()
It restores the internal state of the random number generator
randrange()
This method return the random number between the given range in parameter.
Python program to generate random number
import random
random_number=random.randint(0,5)
print(random_number)
Output:
>>>2
Note: whenever you run above program you will get different number from 0 to 5 in each compilation.
Basics:
- Introduction to Python
- How to install python in your system
- Python comments
- Python Keywords and identifiers
Control statement and loops:
- if statement
- if ..else statement
- if..elif .. else statement
- Nested if..else statement
- for loop
- while loop
- break statement
- continue statement
- pass statement
Data types:
- Python number
- Python list
- Python String
- Python tuple
Python function:
- Function in python with examples
Python oops:
- Python oops
- Python class and object
- Constructor in python
For more detail about python random visit Python.org.