Python Program to Generate a Random Number

Posted in

Python Program to Generate a Random Number
vinaykhatri

Vinay Khatri
Last updated on December 21, 2024

    In this article, we have provided a python code that is capable of generating random numbers.

    Prerequisite to Python Program to Generate a Random Number

    • Python Input, Output
    • python modules

    To generate random numbers in using the python program we require the random module to import in our program.

    Python Program to Generate a Random Number

    import random
    print(random.randint(0,9))

    Output

    8

    If you run this program in your system then you might get a different output. The randint() is a method of random module which is capable of generating random integer values.

    Random Module in Python

    Python has built-in module random which has some set of methods that can be used to generate and manipulate random numbers.

    random methods

    1. choice():

    Choice method is used to pick a random number form a given container such as list, array, tuples, etc.

    Example

    import random
    lis = [132,142,152,249]
    print(random.choice(lis))

    Output

    132

    2. randrange(start, end, steps):

    This method of random can be used to generate a random number but within a range from start to end.

    Example :

    import random
    print(random.randrange(1,200,5))

    Output:

    78

    3. random():

    This method is used to generate a float type random number which is less than 1 and greater than or equal to 0

    Example:

    import random
    print(random.random())

    Output

    0.5812880467507259

    4. shuffle() :

    This method is capable of shuffling the list elements and arrange them randomly.

    Example:

    import random
    lis = [1,2,3,4,5,6,7,8,9,10]
    random.shuffle(lis)
    print(lis)

    Output:

    [8, 6, 5, 2, 9, 10, 3, 4, 7, 1]

    People are also reading:

    Leave a Comment on this Post

    0 Comments