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: Python Program to Generate Random Integers
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 ExamplesPython Tutorials

Python Program to Generate Random Integers

Last updated: Feb 04, 2024 12:36 am
By Meenakshi Agarwal
Share
1 Min Read
Generate Random Integer Numbers
SHARE

In this sample program, you will learn to generate random integer numbers and show the result using the print() function.

Contents
Import the random moduleGenerating a single random integerSample code: Generate random integer numbersGenerating random integers within a rangeUsing random choices from a seqMore examples

Generating random integers in Python

To understand this demo program, you should have the basic Python programming knowledge:

  • Python random module

In the sample below, we are taking the following two inputs from the user and storing them in two different variables.

  • Total number of random numbers to generate
  • The Upper Limit for the random numbers

To generate random integer numbers, you can use Python’s random module and one of its functions known as the randint().

Import the random module

To get started, you need to import the random module. This module offers a range of functions for generating random data. Import it at the beginning of your Python script like this:

import random

To generate multiple random numbers, you should call the randint() inside a Python for loop.

Generating a single random integer

The most straightforward way to generate a single random integer is to use the random.randint() function. It takes two arguments: the lower and upper bounds for the generated number (inclusive). Here’s an example:

import random

# Find a random integer between 3 and including 333
random_number = random.randint(3, 333)

print("Random Integer:", random_number)

Sample code: Generate random integer numbers

# Program to generate random integer numbers

# Import Random Module
import random

count = int(input("How many random numbers do you want to generate? "))
rmax = int(input("Enter Upper Limit for the random numbers: "))

for r in range(count):
    print(random.randint(0, rmax))

The output of the above code is as follows:

How many random numbers do you want to generate? 10
Enter Upper Limit for the random numbers: 1000
703
153
247
481
971
505
794
589
968
126

Generating random integers within a range

Suppose you need random integers within a specific range. In that case, you can use the random.randrange() function, which takes three arguments: start, stop, and step. The start / step arguments are optional.

Here’s an example that generates random integers between 10 and 50 (inclusive) with a step of 5:

import random

# Generate random integers between 10 and 50 (inclusive) with a step of 5
for _ in range(10):
    random_number = random.randrange(10, 55, 5)
    print("Random Integer:", random_number)

In this code, random.randrange(10, 55, 5) will yield random integers between 10 and 55 (inclusive) with intervals of 5.

Generating random integers with a random range

To add an element of surprise, you can generate random integers within a dynamically determined range. Here’s how:

import random

# Determine a random range for the random integers
lower_bound = random.randint(1, 10)
upper_bound = random.randint(11, 20)

# Generate a random integer within the determined range
random_number = random.randint(lower_bound, upper_bound)

print("Lower Bound:", lower_bound)
print("Upper Bound:", upper_bound)
print("Random Integer within Range:", random_number)

In this example, lower_bound and upper_bound are randomly defined, and a random integer is generated within that range.

Using random choices from a seq

In some cases, you might want random integers selected from a predefined sequence of values. The functionrandom.choice() is perfect for this:

import random

# Define a list of possible random integer values
integer_list = [10, 20, 30, 40, 50]

# Generate a random integer from the list
random_number = random.choice(integer_list)

print("Random Integer from List:", random_number)

This code snippet will pick a random integer from the integer_list.

Seeding for Reproducibility

By default, Python’s random module generates pseudorandom numbers. If you want to reproduce the same sequence of random numbers in the future, you can set a seed using random.seed(). This is especially useful for debugging and testing. Here’s an example:

import random

# Set a seed for reproducibility
random.seed(42)

# Generate random integers
for _ in range(5):
    random_number = random.randint(1, 100)
    print("Random Integer:", random_number)

In this example, setting the seed to 42 ensures that the same sequence of random integers will be generated each time the script is run.

More examples

Random integer numbers are useful in a variety of Python applications. For example, they play an important role in creating games, simulations, and statistical models.

Here are a few examples of how you can use random integer numbers in Python applications:

  • Create a dice game: You can use the randint() function to generate random numbers between 1 and 6 to simulate the roll of a die. You can use it to create a variety of dice games, such as craps and Yahtzee.
  • Create a random number generator: You can use the randint() function to create a random number generator that can be used to generate random numbers for a variety of purposes, such as generating passwords or creating random samples of data.
  • Create a simulation: You can use random integer numbers to create simulations of real-world phenomena. For example, you could use random integer numbers to simulate the spread of a disease or the growth of a population.
  • Create a statistical model: You can use random integer numbers to create statistical models of real-world data. For example, you could use random integer numbers to create a model of the distribution of income in a population or the distribution of the number of customers that visit a store each day.

Conclusion

Generating random integers in Python is a common task in many applications. Python’s random module simplifies this process.

Whether you need a single random integer or a series of them, these functions can bring randomness to your Python programs.

Remember that you can set a seed for reproducibility when needed, allowing you to replicate the same sequence of random numbers for testing and debugging purposes.

Cheers!

TechBeamers

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 Python program to swap two numbers Swap Two Numbers Without a Temp in Python
Next Article Check If Python List Contains Elements Of Another List Python List Contains Elements of Another List

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