# Python Random Number Generator – A Step by Step Guide Python Random Number Generator – A Step by Step Guide

A random number is the outcome of a process which arbitrarily chooses it from a sequence. It is called random number generation. With Python random module, we can generate random numbers to fulfill different programming needs. It has a no. of functions like randint(), random(), choice(), uniform() that as a programmer we can decide to use depending on the use case.

At the core, Python uses a Mersenne Twister algorithm, a pseudo-random generator (PRNG) to generate pseudo-random numbers. Its ability to produce uniform results makes it suitable for many applications. Knowing this fact is essential as it would help us determine when to use it and where not.

Studies reveal that PRNGs are suitable for applications such as simulation and modeling but not recommended for cryptographic purposes. And the same rule applies for the Python random number generator. However, we can use it for programming tasks like generating random integers between a range, randomly select an item from a list or shuffle a sequence in place.

Let’s now check out how to use the Python Random Module and see different functions to generate random numbers.

Generate Random Numbers in Python

Table of Content

• 1 How to call random module in Python
• 2 Generate a random number from a range
2.1 randrange(stop)2.2 randrange(start, stop [, step])2.3 random.randint(low, high)* 3 Choose a random value from a sequence
3.1 random.choice(seq)3.2 random.shuffle(list)3.3 random.sample(collection, random list length)* 4 Generate a floating point random number
4.1 random.random()4.2 random.seed()4.3 random.uniform(lower, upper)4.4 random.triangular(low, high, mode)* 5 How to generate a secure random number?
5.1 Python 3.6 secrets module5.2 SystemRandom() class random() method5.3 Directly call the os.urandom()5.4 Convert random bytes into a number* 6 State of random number generator in Python
6.1 random.getstate()6.2 random.setstate(state)6.3 How to call getstate()/setstate()* 7 Using NumPy for random number arrays
7.1 Get a random multi-dimension array of integers7.2 Choose a random value from a sequence* 8 How to generate a universal random number
8.1 What is UUID?8.2 Python UUID module8.3 Why use UUID?8.4 Example* 9 Exercise – Guess the number game using random module
9.1 Logic/Steps9.2 Sample code9.3 Output### How to call random module in Python

The Python Random module provides a range of functions to generate random numbers. So the first thing you should be doing is that import this module in your Python script.

``````import random

``````

Or, you can also try the following syntax.

``````import random

``````

Next, let’s see what you need to do for using the random module.

``````import random

``````

Whenever you run the above piece of code, it’ll give you different output. Below is the one that we saw after executing at our end.

``````import random

``````

Now, you should note the following points from the above example:

• The code is calling the random() which is the most obvious function for random number generation.
• It is one of the pre-requisites for most of the methods in the Random module.
• By default, the random() function generates a float number between 0.0 and 1.0.

Now, we have divided the random number generation into three categories. Each category has some functions to produce desired random values in Python. Let’s check out.

### Generate a random number from a range

#### randrange(stop)

It will produce a random integer value less than the value specified by the [stop] argument.

If “r” is a random number, then its value will lie in the range 0 <= r < stop.

``````import random

``````

You can’t pass zero or negative value or a floating point number to this function as it’ll throw the ValueError exception.

``````import random

``````

Output

``````import random

``````

#### randrange(start, stop [, step])

It uses the following range [start, stop-1] to return a uniquely selected integer value. If the [step] is specified, then the randrange() output is incremented by it.

If “r” is a random number, then its value will lie in the range start <= r < stop.

``````import random

``````

Example

``````import random

``````

Output

``````import random

``````

#### random.randint(low, high)

The randint() function is one of many methods that handle random numbers. It has two parameters low and high and generates an integer between low and high (including both).

Example

``````import random

``````

Output

``````import random

``````

### Choose a random value from a sequence

#### random.choice(seq)

The choice() function arbitrarily determines an element from the given sequence.

Note– A sequence in Python is the generic term for an ordered set like a list, tuple, etc.

Examples

``````import random

``````

#### random.shuffle(list)

The shuffle() function rearranges the items of a list in place so that they occur in a random order.

For shuffling, it uses the Fisher-Yates algorithm which has O(n) complexity. It starts by iterating the last element in the array to the first entry, then swap each entry with a value at a random index below it.

Example

``````import random

``````

Output

``````import random

``````

#### random.sample(collection, random list length)

The sample() function randomly selects N items from a given collection (list, tuple, string, dictionary, set) and returns them as a list.

It works by sampling the items without replacement. It means a single element from the sequence can appear in the resultant list at most once.

Example

``````import random

``````

Output

``````import random

``````

### Generate a floating point random number

#### random.random()

It selects the next random floating point number from the range [0.0, 1.0]. It is a semi-open range as the random function will always return a decimal value which is less than its upper bound. However, it may return 0.

Example

``````import random

``````

Output

``````import random

``````

#### random.seed()

The seed() function performs the initialization of the pseudorandom number generator (PRNG) in Python.

It sets up the seed value which acts as a base to produce a random number. If you don’t provide a seed value, then Python uses the system current time internally.

Example

``````import random

``````

Output:

``````import random

``````

#### random.uniform(lower, upper)

It is an extension of the random() function. In this, you can specify the lower and upper bounds to generate a random number other than the ones between 0 and 1.

Example-1

``````import random

``````

Output

``````import random

``````

Example-2

``````import random

``````

Output

``````import random

``````

#### random.triangular(low, high, mode)

This function generates a float type random number FRN satisfying the below condition:

``````import random

``````

Please note a few points before calling the triangular() method.

• If you don’t specify any of low, high, and mode, then Python takes their values as ZERO, ONE, and the median of the first two values for the MODE.
• It basically does a symmetric distribution.

Example

``````import random

``````

Output

``````import random

``````

### How to generate a secure random number?

We have said at the beginning of this tutorial that PRNGs are not secure by default. So, it is a question mark so far that how do we generate a crypto-safe random number.

A crypto-safe random number is an ideal candidate for cryptographic applications. The data integrity remains critical in such software.

There are three ways in Python to generate a secure random value:

#### Python 3.6 secrets module

First, Python 3.6 introduced a module namely Secrets. It defines functions that can produce cryptographically secure random output. They act under the following conditions:

• The secrets module has methods that generate a sequence of bytes instead of a single integer/float value.
• The output quality will vary depending on the OS of the target machine.

Also, note that the secrets module is available from Python 3.6 not in the below versions.

Example

``````import random

``````

Output

``````import random

``````

#### SystemRandom() class random() method

The second method is to call the SystemRandom() class’s random() method.

Example

``````import random

``````

Output

``````import random

``````

#### Directly call the os.urandom()

Finally, you can directly call the os.urandom() method. The SystemRandom() class also uses this approach internally.

It returns a byte string of the specified size useful for the cryptographic purpose.

Example

``````import random

``````

Output

``````import random

``````

#### Convert random bytes into a number

Two of the above methods provide random bytes instead of an integer value. We can use the binascii module to convert the binary output into an integer value.

Check the below example.

Example

``````import random

``````

Output

``````import random

``````

In the above case, we used the hexlify() function which converts the bytes into an actual random number output. Also, you would have noted that we ran two iterations to show that each gives a different value.

One more point, the above code uses “iter” as a global variable to distinguish between two calls to the main(). Hope, you knew the below fact.

Note: Global variables in Python are accessible without declaring as global. But it is mandatory to do so for changing their values.

### State of random number generator in Python

The random module includes the following two functions to manage the state of the random number generator. Once the state is available, you can use it to reproduce the same random value.

#### random.getstate()

It returns an object carrying the current state of the random generator. You can call the setstate() method with this value to restore the state at any point in time.

Note: By resetting the state, you force the generators to give the same random number again. You should exercise this feature only when needed.

#### random.setstate(state)

It resets the current state of the generator to the input state object. You can fetch the same by calling the random.getstate() function.

#### How to call getstate()/setstate()

If you save the last state and reset it, then it is possible to regenerate the same random number. However, if you change any of the random functions or their parameters, then it will break the logic.

Check out the below sampling example and see how the get/set methods impact the random number generation.

``````import random

``````

Output

``````import random

``````

It is clear from the summary that resetting the state makes the generator return the same sample list in consecutive attempts.

### Using NumPy for random number arrays

NumPy is a scientific computing module in Python. It provides functions to generate multi-dimension arrays.

Since this module isn’t available in Python by default, so you need to pip it first by running:

``````import random

``````

#### Get a random multi-dimension array of integers

• Call random.random_integers(start, stop, size) to generate a 1-d array of random integer numbers between a range
• Call random.random_integers(start, stop, size=(x, y)) to generate a n-d array of random values between [start, stop]

Example

``````import random

``````

#### Choose a random value from a sequence

The numpy module provides the random.choice() method for choosing a random number from the sample list. We can utilize it to select one or more random values from a multi-dimension array.

Example

``````import random

``````

Output

``````import random

``````

To learn more variations on randomization using NumPy, check out this post: Generate Floating Point Random Numbers

It covers how you can generate a floating point random number as well as the array of floats using NumPy.

### How to generate a universal random number

#### What is UUID?

A UUID (Universal Unique Identifier) is a 128-bit long number assigned to an object or entity for unique identification. As per specifications, it is quite unlikely that you can regenerate the same UUID.

#### Python UUID module

Python has a built-in UUID module which generates immutable UUID (Universally Unique Identifier) objects.

All functions in the UUID module are compatible with the available versions of UUID. If you like to generate a cryptographically secure random UUID, then uuid.uuid4() is the recommended function.

#### Why use UUID?

With the help of a unique identifier, it is easy to locate a specific document or user or resources or any information in a database or computer system.

#### Example

``````import random

``````

Output

``````import random

``````

### Exercise – Guess the number game using random module

Dear all, you would have come to the end of this Python random generation guide. Hence, now is the time to test what you have learned from this tutorial.

Your exercise here is to code a famous ‘Guess the Number’ game by using a function from the Python random module.

We are providing our implementation of this game. We used the random.randint(start, stop) to generate a random answer.

#### Logic/Steps

The logic is pretty simple.

• First, you generate a random answer from a specified range by calling a method from the Random module.
• You also set the max number of attempts for the user to limit the retries.
• Run a loop, ask the user to enter his choice, count his attempts.
• Test the input value, if it matches, then stops and greet the user.
• Otherwise, increment the attempts, let the user try until he exceeds the max tries.
• If the user fails to guess the right number, then exit from the loop and display the sorry message.

#### Sample code

``````import random

``````

#### Output

There are two outcomes of the ‘Guess the Numer’ game.

Success – You guessed the right number. Here, the less are your retakes, the better you performed.

``````import random

``````

Failure – You couldn’t guess and exceeded the max attempts.

``````import random

``````
Summary – Generate Random Numbers in Python

We’ve tried to portray the use of the Python random module and its functions in a simplified manner. Our purpose was to make it utterly simple so that even a newbie could understand it easily.

In this tutorial, we covered the most commonly used Python functions to generate random numbers. However, the Python random module also provides methods for advanced random distributions. These include Exponential, Gamma, Gauss, Lognormal, and Pareto distributions.

## Python GUI Programming Projects using Tkinter and Python 3 Python GUI Programming Projects using Tkinter and Python 3

Description
Learn Hands-On Python Programming By Creating Projects, GUIs and Graphics

Python is a dynamic modern object -oriented programming language
It is easy to learn and can be used to do a lot of things both big and small
Python is what is referred to as a high level language
Python is used in the industry for things like embedded software, web development, desktop applications, and even mobile apps!
SQL-Lite allows your applications to become even more powerful by storing, retrieving, and filtering through large data sets easily
If you want to learn to code, Python GUIs are the best way to start!

I designed this programming course to be easily understood by absolute beginners and young people. We start with basic Python programming concepts. Reinforce the same by developing Project and GUIs.

Why Python?

The Python coding language integrates well with other platforms – and runs on virtually all modern devices. If you’re new to coding, you can easily learn the basics in this fast and powerful coding environment. If you have experience with other computer languages, you’ll find Python simple and straightforward. This OSI-approved open-source language allows free use and distribution – even commercial distribution.

When and how do I start a career as a Python programmer?

In an independent third party survey, it has been revealed that the Python programming language is currently the most popular language for data scientists worldwide. This claim is substantiated by the Institute of Electrical and Electronic Engineers, which tracks programming languages by popularity. According to them, Python is the second most popular programming language this year for development on the web after Java.

Python Job Profiles
Software Engineer
Research Analyst
Data Analyst
Data Scientist
Software Developer
Python Salary

The median total pay for Python jobs in California, United States is \$74,410, for a professional with one year of experience
Below are graphs depicting average Python salary by city
The first chart depicts average salary for a Python professional with one year of experience and the second chart depicts the average salaries by years of experience
Who Uses Python?

This course gives you a solid set of skills in one of today’s top programming languages. Today’s biggest companies (and smartest startups) use Python, including Google, Facebook, Instagram, Amazon, IBM, and NASA. Python is increasingly being used for scientific computations and data analysis
Take this course today and learn the skills you need to rub shoulders with today’s tech industry giants. Have fun, create and control intriguing and interactive Python GUIs, and enjoy a bright future! Best of Luck
Who is the target audience?

Anyone who wants to learn to code
For Complete Programming Beginners
For People New to Python
This course was designed for students with little to no programming experience
People interested in building Projects
Basic knowledge
Should have an interest in programming
Interest in learning Python programming
Install Python 3.6 on your computer
What will you learn
Build Python Graphical User Interfaces(GUI) with Tkinter
Be able to use the in-built Python modules for their own projects
Use programming fundamentals to build a calculator
Use advanced Python concepts to code
Build Your GUI in Python programming
Use programming fundamentals to build a Project
Quizzes
Assignments
Job Interview Preparation Questions
& Much More

## Guide to Python Programming Language Guide to Python Programming Language

Description
The course will lead you from beginning level to advance in Python Programming Language. You do not need any prior knowledge on Python or any programming language or even programming to join the course and become an expert on the topic.

The course is begin continuously developing by adding lectures regularly.

Please see the Promo and free sample video to get to know more.

Hope you will enjoy it.

Basic knowledge
An Enthusiast Mind
A Computer
Basic Knowledge To Use Computer
Internet Connection
What will you learn
Will Be Expert On Python Programming Language
Build Application On Python Programming Language

## Python Programming Tutorials For Beginners Python Programming Tutorials For Beginners

Description
Hello and welcome to brand new series of wiredwiki. In this series i will teach you guys all you need to know about python. This series is designed for beginners but that doesn't means that i will not talk about the advanced stuff as well.

As you may all know by now that my approach of teaching is very simple and straightforward.In this series i will be talking about the all the things you need to know to jump start you python programming skills. This series is designed for noobs who are totally new to programming, so if you don't know any thing about

programming than this is the way to go guys Here is the links to all the videos that i will upload in this whole series.

In this video i will talk about all the basic introduction you need to know about python, which python version to choose, how to install python, how to get around with the interface, how to code your first program. Than we will talk about operators, expressions, numbers, strings, boo leans, lists, dictionaries, tuples and than inputs in python. With

Lots of exercises and more fun stuff, let's get started.

Dropbox: https://bit.ly/2AW7FYF

Who is the target audience?

First time Python programmers
Students and Teachers
IT pros who want to learn to code
Aspiring data scientists who want to add Python to their tool arsenal
Basic knowledge
Students should be comfortable working in the PC or Mac operating system
What will you learn
know basic programming concept and skill
build 6 text-based application using python
be able to learn other programming languages
be able to build sophisticated system using python in the future

To know more: