Programs

# How to Generate Random Number in Python [Code with Use Case Examples]

## Introduction to PythonÂ

Python is one of the easiest languages to start learning a program. Python is a general-purpose programming language and designed to increase code readability. It follows an object-oriented approach and enables programmers to write logical and clear codes for small as well as large scale projects. It contains a comprehensive library set that provides many in-built functions for programmers to implement, which makes it easier to use and learn.Â

Let us now move on to know what is random number generation and how toÂ generate random numbers in Python.

## What is Random Number Generation?

Random number generation is the process of producing random numbers whenever required. These numbers can be generated with or without giving conditions. For example, setting the range of numbers from 1 to 100, asking for only even numbers, etc.

Random number generation is one of the most frequently used techniques in programming when we need to input a large number of entities. It is very time-consuming as well as a tedious process when it comes to entering a large number of inputs. Random number generation is also used in case of games; for example, ludo, where we need to generate numbers to roll a dice, or snake and ladder, etc. Some of the other important uses of random number generators are in Cryptography, Monte-Carlo-method simulations, and hash algorithms. If you are a beginner and interested to learn more about data science, check out ourÂ data science coursesÂ from top universities.

As we now know the importance and requirement of random number generation, let us now learn how toÂ generate a random number in Python.

Source

Check out: Python Interview Questions & Answers

## Code to Generate Random Number in Python

As we already know that Python is a general-purpose and an easy-to-learn programming language, let us look upon the codes that enable us to generate random numbers. Python is known for its collection of standard libraries and functions, and similarly, we also have a set of functions that can be used to generate random numbers.Â

These functions are as follows:Â

choice()

The choice() function is used to generate a random number from a built-in container of numbers.Â

random()

The random() function is used to generate a random number, which is of a floating-point number and ranges between 0 and 1.Â

shuffle()

The shuffle() function is used to rearrange all the values present in the provided list randomly.

randint(beginning, end)

The randint() function takes two arguments, beginning, and end, that denote the starting and ending numbers. It produces random integer type numbers between the given starting and ending numbers.Â

randrange(beginning, end, step)

The randrange() function has three arguments- beginning, end, and step, denoting the starting number, ending number, and the steps between numbers. It generates random numbers between the range of beginning and ending number input, in a periodic interval equal to the provided steps.Â

Source

upGrad’s Exclusive Data Science Webinar for you –

Transformation & Opportunities in Analytics & Insights

## Explore our Popular Data Science Online Courses

 Executive Post Graduate Programme in Data Science from IIITB Professional Certificate Program in Data Science for Business Decision Making Master of Science in Data Science from University of Arizona Advanced Certificate Programme in Data Science from IIITB Professional Certificate Program in Data Science and Business Analytics from University of Maryland Data Science Online Courses

The code for using all of these functions toÂ generate random number in PythonÂ is:Â

#importing the random library

import random

# using the choice() function

print(â€˜Generate random number in pythonÂ using the choice() function: â€˜)

print(random.choice([1,2,3,4,5,6]))

print(â€˜\râ€™)

# using the random() function

print(â€˜Generate random number in pythonÂ using the choice() function: â€˜)

print(random.random())

print(â€˜\râ€™)

# using the shuffle() function

# Initializing the list

li = [7, 4, 12, 3, 17]

Â # Printing list before shuffling

print (â€˜The list that is given before shuffling is: â€˜, end=â€™â€™)

for i in range(0, len(li)):

print (li[i], end=â€™â€™ â€˜â€™)Â

print(â€˜\râ€™)

random.shuffle(li)

# Printing the sample list [7, 4, 12, 3, 17] after shuffling

print(â€˜Generate random number in pythonÂ using the shuffle() function: â€˜)

print (â€˜The list after shuffling using the shuffle() function is : â€˜, end=â€™â€™)Â

for i in range(0, len(li)):

print (li[i], end=â€™ â€˜)Â

print(â€˜\râ€™)

#using the randint() function

print(â€˜Generate random number in pythonÂ using the randint() function: â€˜)

print(random.randint(1,10))

print(â€˜\râ€™)

#using the randrange() function

n=10

print(â€˜Generate random number in pythonÂ using the randrange() function: â€˜)

For i in range(1,n):

print(random.randint(0,100,2))

print(â€˜\râ€™)

Learn about: Python Developer Salary in India

Check out All Python tutorial concepts Explained with Examples.

## Bottom line

The Python language has been one of the most demanded programming languages in recent times and is preferred by beginners as well as experienced programmers. Python is used for server-side for web-development, software development, mathematics, and also for system scripting. There are various interesting projects and articles on Python that you can find on our blog. Python is also majorly used for Data Science and Machine Learning.

## Top Data Science Skills to Learn to upskill

 SL. No Top Data Science Skills to Learn 1 Data Analysis Online Courses Inferential Statistics Online Courses 2 Hypothesis Testing Online Courses Logistic Regression Online Courses 3 Linear Regression Courses Linear Algebra for Analysis Online Courses

If you are interested in Data Science and Machine Learning and are curious to learn it, you can visit upGradâ€™s courses made by industry experts as well as experienced academicians. These courses are made for working professionals who want to change their careers or advance in their respective fields. These are some of the courses that you can complete to know more about these technologies.Â

Executive PG Program (NASSCOM certified Diploma course in Data Science developed by upGrad in coordination with IIITB)

Associate Certificate Program in Data Science (PG certification course developed by upGrad along with IIITB with hands-on industry projects, expert mentorship, and 24×7 support)

Executive PG Programme in Machine Learning and AI (PG Diploma course in Machine Learning and AI provided by IIITB and upGrad )

Masters of Science in Data Science (Masters course in Data Science provided by Liverpool John Moores University and upGrad)

Masters of Science in Machine Learning and AI (Masterâ€™s course in AI and Machine Learning provided by upGrad along with IIITB and Liverpool John Moores University )

## What are the most common errors made while writing Python code?

Some of the common errors made while writing Python code are:-

1. The most frequent cause of an error in a Python program is when a statement is not used correctly. A syntax error is a kind of mistake like this. The Python interpreter notifies you right away in such a case.

2. Most people make the mistake of not including colons after the loop syntax.

3. A common logical mistake is using two variables in the same application.

4. When an error happens at the runtime after passing the syntax test, it is referred to as an exception or logical type. When we divide any integer by zero, we get the ZeroDivisionError exception, and when we import a module that doesn't exist, we get the ImportError alert.

## What is the best program to learn Python?

Jupyter Notebook is a useful tool for learning Python. Users can use Jupyter Notebook to combine data, code, and text to create an interactive computational story. Also, data scientists can use it to streamline end-to-end data science operations. Jupyter Notebook enables you to share Python code in real time with others. On the same page, you can view both the code and the results. It's useful to refer to other people's work as a learning resource. You may execute the code cell by cell to gain a better grasp of what it does. You can get started with the learning process by installing Jupyter Notebook using the Python pip command.

## What are some other use cases to generate random numbers in Python?

One of the simplest and most common ways to generate random numbers in Python is to write a code that contains a random set of numbers such as 7,4,12,18, or any other similar set. There are, however, additional options that can provide the desired outcome. There are several computer ways for generating random numbers. You can create code to simulate the rolling of dice, coin flipping, and shuffling of playing cards to generate a random number. Gambling, statistical sampling, computer simulation, cryptography, totally randomized design, and other areas where creating an unpredictable outcome is desirable use such codes for making the work easier.