TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Generate a Python Random Number
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Generate a Python Random Number

Last updated: Apr 23, 2024 10:34 pm
By Meenakshi Agarwal
Share
9 Min Read
Python random number tutorial
SHARE

Here is a quick guide on Python’s random number. You can always refer to it whenever you need to generate a random number in your programs. Python has a built-in random module for this purpose. It exposes several methods such as randrange(), randint(), random(), seed(), uniform(), etc. You can call any of these functions to generate a Python random number.

Contents
What is a Random Number Generator?What is Python Random Module?Python randrange() MethodSyntaxExample-1Example-2Python randint() MethodSyntaxExamplePython random() MethodSyntaxExamplePython seed() MethodSyntaxHow to Use Seed() with random()Python uniform() MethodSyntaxPython Random Numbers Using uniform()More Related Tutorials

Multiple Ways to Generate Random Numbers in Python

Usually, a random number is an integer, but you can generate float random also. However, you first need to understand the context as a programmer and then pick the right function to use.

Python random number tutorial

What is a Random Number Generator?

A random number generator is a deterministic system that produces pseudo-random numbers. It uses the Mersenne Twister algorithm that can generate a list of random numbers.

A deterministic algorithm always returns the same result for the same input.

It is by far the most successful PRNG technique implemented in various programming languages.

A pseudo-random number is statistically random, but has a defined starting point and may repeat itself.

What is Python Random Module?

Python has built-in support for generating numbers by using the random module. It has many functions to produce random numbers depending on your needs. These values are pseudo-random numbers. They are generated using algorithms that depend on an initial value called a seed.

Let’s now check out some real examples to generate random integer and float numbers.

Python randrange() Method

The randrange() function is available with the Python random module. It can help you produce a random number from a given range of values.

This function has the following three variations:

Syntax

# Type:1 randrange() with all three arguments
random.randrange(begin, end, step counter)

While using this form of randrange(), you have to pass the start, stop, and step values.

# Type:2 randrange() with first two arguments
random.randrange(begin, end)

With this form, you provide the start and stop, and the default (=1) is used as the step counter.

# Type:3 randrange() with a single argument
random.randrange(end)

You only need to pass the endpoint of the range. The value (=0) is considered for the starting point and the default (=1) for the step counter.

Also, please note the end/stop value is excluded while generating a random number. This function produces the ValueError exception in the following cases:

  • If you have used a float range for the start/stop/step.
  • Or if the start value is more than the stop value.

Let’s now check out a few examples.

Example-1

import random as rand

# Generate random number between 0 to 100

# Pass all three arguments in randrange()
print("First Random Number: ", rand.randrange(0, 100, 1))

# Pass first two arguments in randrange()
# Default step = 1
print("Second Random Number: ", rand.randrange(0, 100))

# Or, you can only pass the start argument
# Default start = 0, step = 1
print("Third Random Number: ", rand.randrange(100))

The output is:

First Random Number:  3
Second Random Number:  36
Third Random Number:  60

Example-2

import random as rand

# Generate random number between 1 to 99

# Pass all three arguments in randrange()
print("First Random Number: ", rand.randrange(1, 99, 1))

# Pass first two arguments in randrange()
# Default step = 1
print("Second Random Number: ", rand.randrange(1, 99))

The result is:

First Random Number:  18
Second Random Number:  77

Python randint() Method

The randint() function is somewhat similar to the randrange(). It, too, generates a random integer number from the range. However, it differs a bit:

  • Randint() has two mandatory arguments: start and stop
  • It has an inclusive range, i.e., can return both endpoints as the random output.

Syntax

# random module's randint() function
random.randint(start, stop)

This function considers both the beginning and end values while generating the random output.

Example

import random as rand

# Generate random number using randint()

# Simple randint() example
print("Generate First Random Number: ", rand.randint(10, 100))

# randint() along with seed()
rand.seed(10)
print("Generate Second Random Number: ", rand.randint(10, 100))

rand.seed(10)
print("Repeat Second Random Number: ", rand.randint(10, 100))

The following is the result:

Generate First Random Number:  14
Generate Second Random Number:  83
Repeat Second Random Number:  83

Python random() Method

It is one of the most basic functions of the Python random module. It computes a random float number between 0 and 1.

This function has the following syntax:

Syntax

# random() function to generate a float number
random.random()

Example

import random as rand

# Generate random number between 0 and 1

# Generate first random number
print("First Random Number: ", rand.random())

# Generate second random number
print("Second Random Number: ", rand.random())

The following is the output after execution:

First Random Number:  0.6448613829842063
Second Random Number:  0.9482605596764027

Python seed() Method

The seed() is a special method of the Python random module. It lets you control the state of the random() function. It means that once you set a seed value and call random(). Python then maps the given seed to the output of this operation.

So, whenever you call seed() with the same value, the subsequent random() returns the same random number.

Syntax

# random seed() function
random.seed([seed value])

The seed is an optional field. Its default value is None, which means to use the system time for random operation.

How to Use Seed() with random()

import random as rand

# Generate random number using seed()

# Using seed() w/o any argument
rand.seed()
print("Generate First Random Number: ", rand.random())
rand.seed()
print("Generate Second Random Number: ", rand.random())

# Using seed() with an argument
rand.seed(5)
print("Generate Third Random Number: ", rand.random())
rand.seed(5)
print("Repeat Third Random Number: ", rand.random())

Here is the execution result:

Generate First Random Number:  0.6534144429163206
Generate Second Random Number:  0.4590722400270483
Generate Third Random Number:  0.6229016948897019
Repeat Third Random Number:  0.6229016948897019

Please note that you can even pair up seed() with other Python random functions such as randint() or randrange().

Python uniform() Method

The uniform() function computes a random float number from the given range. It takes two arguments to specify the range.

The first parameter is inclusive of random processing.

Syntax

# random uniform() function
random.uniform(start, stop)

This function provides a random result (r) satisfying the start <= r < stop. Also, please note that both the start and stop parameters are mandatory.

Python Random Numbers Using uniform()

import random as rand

# Generate random float number using uniform()

# Simple randint() example
print("Generate First Random Float Number: ", rand.uniform(10, 100))
print("Generate Second Random Float Number: ", rand.uniform(10, 100))

The result after execution is:

Generate First Random Float Number:  20.316562022174068
Generate Second Random Float Number:  27.244409254588806

More Related Tutorials

Generate a Random Number List in Python
Generate Random Characters in Python
A Guide to Python Random Sampling
Generate Random Images in Python
Python Code to Generate Random Email
Python Code to Generate Random Integers

Now, we have come to the end of this Python random number generator tutorial. We hope that it will help you lead in the right direction. You may also like to read the other tutorials on our blog.

Quick Reference

1. https://docs.python.org/3/library/random.html

Happy coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

TAGGED:Random Data Generation Made Easy
Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Java ArrayList Explained with Examples How to Use ArrayList in Java
Next Article SQL Exercises with Sample Table and Demo Data SQL Exercises – Complex Queries

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x