Random Library in Python

June 03, 2021


Python is an easy-to-read and easy-to-learn coding language, it has a simple approach to coding small and large projects. This language is widely used across the world and is useful for many types of projects.

Python Libraries

Python is a great coding language alone, but more features can be added by importing libraries. By importing libraries, we are able to add more functions and opportunities for other projects. At times, the imported library can provide solutions to difficult problems than just using the regular Python language. 

Import a library at the beginnging of the code with:

import libraryname

Random Library

The random library is a collection of functions that all have to do with randomization. This library uses a certain algorithm or equation to add randomness, so in a way, it is not true randomization. However, the library can be useful for small and personal projects.

Import the random library:

import random

Generating a Random Integer

To generate a random whole number, we would use the randint() function. This chooses a random number within a range.

To use this function with a range of 10:


It starts with saying which library the function is from: random, and then says which function from the library: randint, which is short for random integer. This specific functions needs a range to be given within the parentheses so it can have a real set of numbers to use for its algorithm.This function is useful for a number of different project that can be done. 

Code Walk-Through 

import random

  • Adds the random library to the code, so that way we can access its functions.

answer = input("Do you like summer?")

  • Creates a variable 'answer,' and makes it equal to the what the user types after printing 'Do you like summer?'

if(answer == 'yes'):

    randomnum = random.randint(0,1)

  • If the answer is equal to 'yes,' then it will use the random function to choose between two possible responses.

    if(randomnum == 0):

        print("Have a great summer!")

  • If the random number is equal to '0,' then the computer will print 'Have a great summer!'

    if(randomnum == 1):

        print("Don't forget to practice coding!")

  • If the random number is equal to '1,' then the computer will print 'Don't forget to practice coding!'

By increasing the range and adding more if statements, it is easy to create many more reponses.


By using libraries in Python, more functions are able to be added and used. Understanding the concept of libraries can greatly impact the future of a programmer. Let's keep learning the different types of libraries that can be used!