Python Random

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:

  1. Introduction to Python
  2. How to install python in your system
  3. Python comments
  4. Python Keywords and identifiers

Control statement and loops:

  1. if statement
  2. if ..else statement
  3. if..elif .. else statement
  4. Nested if..else statement
  5. for loop
  6. while loop
  7. break statement
  8. continue statement
  9. pass statement

Data types:

  1. Python number
  2. Python list
  3. Python String
  4. Python tuple

Python function:

  1. Function in python with examples

Python oops:

  1. Python oops
  2. Python class and object
  3. Constructor in python

For more detail about python random visit Python.org.

Leave a Reply