Chuyển tới nội dung
Home » From Random Import Randint Python | Parameter Values

From Random Import Randint Python | Parameter Values

random numbers in python

Random Numbers with the Python Standard Library

The Python standard library provides a module called random that offers a suite of functions for generating random numbers.

Python uses a popular and robust pseudorandom number generator called the Mersenne Twister.

In this section, we will look at a number of use cases for generating and using random numbers and randomness with the standard Python API.

Need help with Statistics for Machine Learning?

Take my free 7-day email crash course now (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

Seed The Random Number Generator

The pseudorandom number generator is a mathematical function that generates a sequence of nearly random numbers.

It takes a parameter to start off the sequence, called the seed. The function is deterministic, meaning given the same seed, it will produce the same sequence of numbers every time. The choice of seed does not matter.

The seed() function will seed the pseudorandom number generator, taking an integer value as an argument, such as 1 or 7. If the seed() function is not called prior to using randomness, the default is to use the current system time in milliseconds from epoch (1970).

The example below demonstrates seeding the pseudorandom number generator, generates some random numbers, and shows that reseeding the generator will result in the same sequence of numbers being generated.

10

11

# seed the pseudorandom number generator

from random import seed

from random import random

# seed random number generator

seed(1)

# generate some random numbers

print(random(), random(), random())

# reset the seed

seed(1)

# generate some random numbers

print(random(), random(), random())

Running the example seeds the pseudorandom number generator with the value 1, generates 3 random numbers, reseeds the generator, and shows that the same three random numbers are generated.

0.13436424411240122 0.8474337369372327 0.763774618976614

0.13436424411240122 0.8474337369372327 0.763774618976614

It can be useful to control the randomness by setting the seed to ensure that your code produces the same result each time, such as in a production model.

For running experiments where randomization is used to control for confounding variables, a different seed may be used for each experimental run.

Random Floating Point Values

Random floating point values can be generated using the random() function. Values will be generated in the range between 0 and 1, specifically in the interval [0,1).

Values are drawn from a uniform distribution, meaning each value has an equal chance of being drawn.

The example below generates 10 random floating point values.

# generate random floating point values

from random import seed

from random import random

# seed random number generator

seed(1)

# generate random numbers between 0-1

for _ in range(10):

value = random()

print(value)

Running the example generates and prints each random floating point value.

10

0.13436424411240122

0.8474337369372327

0.763774618976614

0.2550690257394217

0.49543508709194095

0.4494910647887381

0.651592972722763

0.7887233511355132

0.0938595867742349

0.02834747652200631

The floating point values could be rescaled to a desired range by multiplying them by the size of the new range and adding the min value, as follows:

scaled value = min + (value * (max – min))

Where min and max are the minimum and maximum values of the desired range respectively, and value is the randomly generated floating point value in the range between 0 and 1.

Random Integer Values

Random integer values can be generated with the randint() function.

This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end]. Random values are drawn from a uniform distribution.

The example below generates 10 random integer values between 0 and 10.

# generate random integer values

from random import seed

from random import randint

# seed random number generator

seed(1)

# generate some integers

for _ in range(10):

value = randint(0, 10)

print(value)

Running the example generates and prints 10 random integer values.

10

10

Random Gaussian Values

Random floating point values can be drawn from a Gaussian distribution using the gauss() function.

This function takes two arguments that correspond to the parameters that control the size of the distribution, specifically the mean and the standard deviation.

The example below generates 10 random values drawn from a Gaussian distribution with a mean of 0.0 and a standard deviation of 1.0.

Note that these parameters are not the bounds on the values and that the spread of the values will be controlled by the bell shape of the distribution, in this case proportionately likely above and below 0.0.

# generate random Gaussian values

from random import seed

from random import gauss

# seed random number generator

seed(1)

# generate some Gaussian values

for _ in range(10):

value = gauss(0, 1)

print(value)

Running the example generates and prints 10 Gaussian random values.

10

1.2881847531554629

1.449445608699771

0.06633580893826191

-0.7645436509716318

-1.0921732151041414

0.03133451683171687

-1.022103170010873

-1.4368294451025299

0.19931197648375384

0.13337460465860485

Note: In the random module, there is a function

normalvariate()

that functions the same as

gauss()

. The former is thread-safe while

gauss()

is not. However, you rarely run Python in multithread and

gauss()

is faster.

Randomly Choosing From a List

Random numbers can be used to randomly choose an item from a list.

For example, if a list had 10 items with indexes between 0 and 9, then you could generate a random integer between 0 and 9 and use it to randomly select an item from the list. The choice() function implements this behavior for you. Selections are made with a uniform likelihood.

The example below generates a list of 20 integers and gives five examples of choosing one random item from the list.

10

11

12

# choose a random element from a list

from random import seed

from random import choice

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# make choices from the sequence

for _ in range(5):

selection = choice(sequence)

print(selection)

Running the example first prints the list of integer values, followed by five examples of choosing and printing a random value from the list.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

18

Random Subsample From a List

We may be interested in repeating the random selection of items from a list to create a randomly chosen subset.

Importantly, once an item is selected from the list and added to the subset, it should not be added again. This is called selection without replacement because once an item from the list is selected for the subset, it is not added back to the original list (i.e. is not made available for re-selection).

This behavior is provided in the sample() function that selects a random sample from a list without replacement. The function takes both the list and the size of the subset to select as arguments. Note that items are not actually removed from the original list, only selected into a copy of the list.

The example below demonstrates selecting a subset of five items from a list of 20 integers.

10

11

# select a random sample without replacement

from random import seed

from random import sample

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# select a subset without replacement

subset = sample(sequence, 5)

print(subset)

Running the example first prints the list of integer values, then the random sample is chosen and printed for comparison.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[4, 18, 2, 8, 3]

Randomly Shuffle a List

Randomness can be used to shuffle a list of items, like shuffling a deck of cards.

The shuffle() function can be used to shuffle a list. The shuffle is performed in place, meaning that the list provided as an argument to the shuffle() function is shuffled rather than a shuffled copy of the list being made and returned.

The example below demonstrates randomly shuffling a list of integer values.

10

11

# randomly shuffle a sequence

from random import seed

from random import shuffle

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# randomly shuffle the sequence

shuffle(sequence)

print(sequence)

Running the example first prints the list of integers, then the same list after it has been randomly shuffled.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[11, 5, 17, 19, 9, 0, 16, 1, 15, 6, 10, 13, 14, 12, 7, 3, 8, 2, 18, 4]

Further Reading: Probability Theory and Statistical Analysis

If you’re interested in the theory behind random number generation, consider studying probability theory. And if you want to apply random number generation in data analysis, look into statistical analysis in Python. Both topics will provide a deeper understanding of the power and potential of Python’s

randint()

function.

Further Resources for Python Modules

For a more profound understanding of Python Modules, we have gathered several insightful resources for you:

  • Python Modules Fundamentals Covered – Dive deep into Python’s module caching and reload mechanisms.
  • Implementing Queues in Python – Dive into various queue types, including FIFO and LIFO, in Python.

  • Simplifying Random Data Generation in Python – Learn how to add randomness to your Python programs with “random.”

  • Python’s Random Module – Learn about the random module and generating random numbers with this Programiz guide.

  • How to Create Random Numbers in Python – A Medium article that delves into generating random numbers in Python.

  • Python’s Random Tutorial – A tutorial by Real Python covering topics related to generating random numbers in Python.

Explore these resources, and you’ll be taking another stride towards expertise in Python and taking your coding abilities to the next level.

random numbers in python
random numbers in python

Python3


import


random


r2


random.randint(


'a'


'z'


print


(r2)

Output :

Traceback (most recent call last):
File “/home/fb805b21fea0e29c6a65f62b99998953.py”, line 5, in
r2=random.randint(‘a’, ‘z’)
File “/usr/lib/python3.5/random.py”, line 218, in randint
return self.randrange(a, b+1)
TypeError: Can’t convert ‘int’ object to str implicitly

Applications : The randint() function can be used to simulate a lucky draw situation. Let’s say User has participated in a lucky draw competition. The user gets three chances to guess the number between 1 and 10. If guess is correct user wins, else loses the competition.

Random Numbers

To generate random numbers, first import the randint command section from Python’s random code library on the first line of the program.

The randint command stands for random integer. In brackets, state the number range to randomly choose from.

The random value should be saved into a variable.

from random import randint

number = randint(1,100)

print(“A random number between 1 and 100 is” , number)

A random number between 1 and 100 is 39

A random number between 1 and 100 is 73

A random number between 1 and 100 is 4

The randint range does not have to be fixed values and could be replaced by variables.

Below is a program where the user selects the upper and lower values of the range:

from random import randint

lower = int(input(“What is the lowest number? “))

upper = int(input(“What is the highest number? “))

number = randint(lower,upper)

print(“A random number between” , lower , “and” , upper , “is” , number)

What is the lowest number? 1What is the highest number? 50A random number between 1 and 50 is 36

What is the lowest number? 500What is the highest number? 1000A random number between 500 and 1000 is 868

Random Numbers Task 1 (Ice Comet)

A special comet made of ice passes the Earth only once every one hundred years, and it hasn’t been seen yet in the 21st century.

Use the randint command to randomly print a year between the current year and 2099.

Example solutions:

Did you know it won’t be until 2032 that the ice comet will next pass Earth!?

Did you know it won’t be until 2075 that the ice comet will next pass Earth!?

Random Numbers Task 2 (Guess the Number)

Use randint to generate a random number between 1 and 5.

Ask the user to enter a guess for the number with int and input.

Print the random number and use an if statement to check if there is a match, printing an appropriate statement if there is and something different if there is not a match.

Example solutions:

Enter a number between 1 and 5: 4Computer’s number: 5No match this time!

Enter a number between 1 and 5: 3Computer’s number: 3Well guessed! It’s a match!

Unit 3 - Built in Functions,  Importing Random, and Using randint function - Python
Unit 3 – Built in Functions, Importing Random, and Using randint function – Python

Further Reading: Probability Theory and Statistical Analysis

If you’re interested in the theory behind random number generation, consider studying probability theory. And if you want to apply random number generation in data analysis, look into statistical analysis in Python. Both topics will provide a deeper understanding of the power and potential of Python’s

randint()

function.

Further Resources for Python Modules

For a more profound understanding of Python Modules, we have gathered several insightful resources for you:

  • Python Modules Fundamentals Covered – Dive deep into Python’s module caching and reload mechanisms.
  • Implementing Queues in Python – Dive into various queue types, including FIFO and LIFO, in Python.

  • Simplifying Random Data Generation in Python – Learn how to add randomness to your Python programs with “random.”

  • Python’s Random Module – Learn about the random module and generating random numbers with this Programiz guide.

  • How to Create Random Numbers in Python – A Medium article that delves into generating random numbers in Python.

  • Python’s Random Tutorial – A tutorial by Real Python covering topics related to generating random numbers in Python.

Explore these resources, and you’ll be taking another stride towards expertise in Python and taking your coding abilities to the next level.

Expanding the Range of randint

Python’s

randint()

function isn’t limited to small ranges. In fact, you can generate random integers in any range you like. For example, if you’re simulating a lottery draw, you might need to generate numbers between 1 and 1000:


import random lottery_number = random.randint(1, 1000) print(lottery_number) # Output: # (A random number between 1 and 1000)

In this example, we’ve expanded the range of

randint()

to generate a random number between 1 and 1000. This demonstrates the flexibility of the

randint()

function.

Python Tutorial: Generate Random Numbers and Data Using the random Module
Python Tutorial: Generate Random Numbers and Data Using the random Module

Understanding Python’s randint Function

Python’s

randint()

is a function that belongs to the

random

module. It is used to generate a random integer within a defined range. The function takes two parameters: the start and end of the range, inclusive.

Using randint: A Simple Example

Let’s look at a simple code example to understand how

randint()

works:


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

In this example,

import random

is used to import the random module, which contains the randint function. Next,

random.randint(1, 10)

is used to generate a random integer between 1 and 10, inclusive. The result is then stored in the variable

number

, which is printed out.

Parameters and Return Value

The

randint(a, b)

function takes two parameters:

  • : The lower limit of the range (inclusive).
  • : The upper limit of the range (inclusive).

The function returns a random integer such that

a <= N <= b

.

Understanding the Output

The output of the

randint()

function is a random integer within the specified range. In our example, the output is a random number between 1 and 10. Each time you run the code, you might get a different number because the selection is random.

By understanding the basics of Python’s

randint()

function, you can start to harness the power of random number generation in your coding projects.

Random Numbers with NumPy

In machine learning, you are likely using libraries such as scikit-learn and Keras.

These libraries make use of NumPy under the covers, a library that makes working with vectors and matrices of numbers very efficient.

NumPy also has its own implementation of a pseudorandom number generator and convenience wrapper functions.

NumPy also implements the Mersenne Twister pseudorandom number generator.

Let’s look at a few examples of generating random numbers and using randomness with NumPy arrays.

Seed The Random Number Generator

The NumPy pseudorandom number generator is different from the Python standard library pseudorandom number generator.

Importantly, seeding the Python pseudorandom number generator does not impact the NumPy pseudorandom number generator. It must be seeded and used separately.

The seed() function can be used to seed the NumPy pseudorandom number generator, taking an integer as the seed value.

The example below demonstrates how to seed the generator and how reseeding the generator will result in the same sequence of random numbers being generated.

10

11

# seed the pseudorandom number generator

from numpy.random import seed

from numpy.random import rand

# seed random number generator

seed(1)

# generate some random numbers

print(rand(3))

# reset the seed

seed(1)

# generate some random numbers

print(rand(3))

Running the example seeds the pseudorandom number generator, prints a sequence of random numbers, then reseeds the generator showing that the exact same sequence of random numbers is generated.

[4.17022005e-01 7.20324493e-01 1.14374817e-04]

[4.17022005e-01 7.20324493e-01 1.14374817e-04]

Array of Random Floating Point Values

An array of random floating point values can be generated with the rand() NumPy function.

If no argument is provided, then a single random value is created, otherwise the size of the array can be specified.

The example below creates an array of 10 random floating point values drawn from a uniform distribution.

# generate random floating point values

from numpy.random import seed

from numpy.random import rand

# seed random number generator

seed(1)

# generate random numbers between 0-1

values = rand(10)

print(values)

Running the example generates and prints the NumPy array of random floating point values.

[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01

1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01

3.96767474e-01 5.38816734e-01]

Array of Random Integer Values

An array of random integers can be generated using the randint() NumPy function.

This function takes three arguments, the lower end of the range, the upper end of the range, and the number of integer values to generate or the size of the array. Random integers will be drawn from a uniform distribution including the lower value and excluding the upper value, e.g. in the interval [lower, upper).

The example below demonstrates generating an array of random integers.

# generate random integer values

from numpy.random import seed

from numpy.random import randint

# seed random number generator

seed(1)

# generate some integers

values = randint(0, 10, 20)

print(values)

Running the example generates and prints an array of 20 random integer values between 0 and 10.

[5 8 9 5 0 0 1 7 6 9 2 4 5 2 4 2 4 7 7 9]

Array of Random Gaussian Values

An array of random Gaussian values can be generated using the randn() NumPy function.

This function takes a single argument to specify the size of the resulting array. The Gaussian values are drawn from a standard Gaussian distribution; this is a distribution that has a mean of 0.0 and a standard deviation of 1.0.

The example below shows how to generate an array of random Gaussian values.

# generate random Gaussian values

from numpy.random import seed

from numpy.random import randn

# seed random number generator

seed(1)

# generate some Gaussian values

values = randn(10)

print(values)

Running the example generates and prints an array of 10 random values from a standard Gaussian distribution.

[ 1.62434536 -0.61175641 -0.52817175 -1.07296862 0.86540763 -2.3015387

1.74481176 -0.7612069 0.3190391 -0.24937038]

Values from a standard Gaussian distribution can be scaled by multiplying the value by the standard deviation and adding the mean from the desired scaled distribution. For example:

scaled value = mean + value * stdev

Where mean and stdev are the mean and standard deviation for the desired scaled Gaussian distribution and value is the randomly generated value from a standard Gaussian distribution.

Shuffle NumPy Array

A NumPy array can be randomly shuffled in-place using the shuffle() NumPy function.

The example below demonstrates how to shuffle a NumPy array.

10

11

# randomly shuffle a sequence

from numpy.random import seed

from numpy.random import shuffle

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# randomly shuffle the sequence

shuffle(sequence)

print(sequence)

Running the example first generates a list of 20 integer values, then shuffles and prints the shuffled array.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[3, 16, 6, 10, 2, 14, 4, 17, 7, 1, 13, 0, 19, 18, 9, 15, 8, 12, 11, 5]

Modern Ways of Random Number Generation in NumPy

In newer version of NumPy, you can do random number generation the following way:

10

11

12

13

14

15

16

import numpy as np

rng = np.random.Generator(np.random.PCG64())

rng = np.random.default_rng()

# uniform from 0 to 1

value = rng.random()

# generate 10 Gaussian random number

value = rng.standard_normal(10)

# generate 20 random integers between 0 and 10

value = rng.integers(low=0, high=10, size=20)

# shuffle a sequence in-place

rng.shuffle(sequence)

The object

rng

is a random number generator. You can create multiple such generators, or use the default one. The idea is to allow you to have multiple independent random number generator so drawing random numbers from one generator would not affect another. This would make your code more robust (because you can mitigate the race condition in parallel algorithms) and allows you to fine-tune the pseudo-random number generation algorithm.

Python Random Module Functions - Coding Examples (random, randint, choice, randrange)
Python Random Module Functions – Coding Examples (random, randint, choice, randrange)

TL;DR: How Do I Use the randint Function in Python?

The randint function is part of Python’s random module, and it’s used to generate a random integer within a specified range. Here’s a simple example:


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

In this example, we’re using Python’s

random.randint()

function to generate a random number between 1 and 10. The

import random

line at the beginning is necessary because randint is part of the random module in Python. The function

random.randint(1, 10)

then generates a random integer within the range of 1 and 10.

If you’re interested in learning more about the randint function, including its more advanced uses and potential issues you might encounter, keep reading for a comprehensive exploration.

Table of Contents

  • Understanding Python’s randint Function
  • Expanding the Range of randint
  • Using randint in Loops
  • Exploring Alternatives to randint
  • Common Issues and Solutions with randint
  • Best Practices with randint
  • Understanding Random Number Generation in Python
  • Real-World Applications of Python’s randint
  • Further Reading: Probability Theory and Statistical Analysis
  • Wrapping Up: Python’s randint Function

Summing It Up

In this article, you learned everything about the randint Python function. You also learned something fun, which was creating a lucky draw game that you can enjoy in your free time. You can also tweak that code to make it a bit more complex for a bigger lucky draw game.

It is fascinating to see how one can do so much with Python programming. If you want to learn more about Python’s concepts, you can refer to Simplilearn’s Python Tutorial for Beginners. The tutorial is dedicated to newbies to help them get acquainted with Python’s basics. Once you are done with the basics, you can opt for our Post Graduate Program in Full Stack Web Development course to learn the advanced concepts and excel in Python development.

Have any questions for us? Leave them in the comments section, and our experts will answer them for you ASAP!

Is “randint” a function? Or is it just imported?

Codeacademy automatically adds this code on the top.


from random import randint

What does this function do? I can pass the sections from 7/9 – 9/9 with or without this function. Here is the complete code.


from random import randint board = [] for x in range(0,5): board.append(["O"] * 5) def print_board(board): for row in board: print " ".join(row) def random_row(board): return randint(0, len(board) - 1) def random_col(board): return randint(0, len(board[0]) - 1) ship_row = random_row(board) ship_col = random_col(board) print ship_col print ship_row # Add your code below! guess_row = int(raw_input("Guess Row:")) guess_col = int(raw_input("Guess Col:"))

python from random import randint
python from random import randint

Wrapping Up: Python’s randint Function

Python’s

randint()

function is a powerful tool in the

random

module, providing a straightforward way to generate random integers within a specified range. From simple applications to more complex scenarios,

randint()

offers a reliable solution for random number generation.

While

randint()

is generally easy to use, common issues include forgetting to import the

random

module and using incorrect range values. These can be easily avoided by following best practices such as always importing necessary modules and ensuring correct parameter values.

Beyond

randint()

, Python offers other methods for random number generation. These include the

random()

and

uniform()

functions in the

random

module, and the

numpy.random.randint()

function in the NumPy module. Each method has its unique advantages and can be more suitable depending on your specific needs.

Random number generation is a fundamental aspect of programming with diverse applications. By mastering Python’s

randint()

function and understanding other random number generation methods, you can harness the power of randomness in your Python projects.

The use of randomness is an important part of the configuration and evaluation of machine learning algorithms.

From the random initialization of weights in an artificial neural network, to the splitting of data into random train and test sets, to the random shuffling of a training dataset in stochastic gradient descent, generating random numbers and harnessing randomness is a required skill.

In this tutorial, you will discover how to generate and work with random numbers in Python.

After completing this tutorial, you will know:

  • That randomness can be applied in programs via the use of pseudorandom number generators.
  • How to generate random numbers and use randomness via the Python standard library.
  • How to generate arrays of random numbers via the NumPy library.

Kick-start your project with my new book Statistics for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.

Let’s get started.

How to Generate Random Numbers in PythonPhoto by Thomas Lipike. Some rights reserved.

Real-World Applications of Python’s randint

Python’s

randint()

function isn’t just for academic exercises—it has practical applications in real-world scenarios. Let’s explore some of these applications.

Simulations

In simulations,

randint()

can be used to generate random inputs. For example, in a weather simulation,

randint()

could generate random temperatures or wind speeds.


import random random_temperature = random.randint(-10, 40) print('Random Temperature:', random_temperature, '°C') # Output: # Random Temperature: (A random number between -10 and 40) °C

In this code, we’re using

randint()

to generate a random temperature between -10 and 40 degrees Celsius.

Games

In games,

randint()

can be used to create unpredictable elements, making the game more exciting. For instance, in a dice game,

randint()

could be used to generate the dice roll.


import random dice_roll = random.randint(1, 6) print('Dice Roll:', dice_roll) # Output: # Dice Roll: (A random number between 1 and 6)

In this code, we’re using

randint()

to simulate a dice roll, generating a random number between 1 and 6.

Data Analysis

In data analysis,

randint()

can be used to generate random samples from a larger dataset. This can ensure a more representative sample and more accurate analysis.

random.randint error - python
random.randint error – python

Understanding Random Number Generation in Python

Random number generation is a fundamental concept in programming that has a variety of applications, from game development to data analysis. Python’s

random

module, which includes the

randint()

function, is a powerful tool for generating these random numbers.

The Role of Python’s Random Module

Python’s

random

module provides a suite of functions for generating random numbers. These functions include

randint()

,

random()

,

uniform()

, and many others. Each function generates a random number in a different way or within a different range.


import random random_integer = random.randint(1, 10) random_float = random.random() random_uniform = random.uniform(1.0, 10.0) print(random_integer, random_float, random_uniform) # Output: # (A random integer between 1 and 10, a random float between 0.0 and 1.0, a random float between 1.0 and 10.0)

In this code, we’re using three functions from Python’s

random

module to generate different types of random numbers. Each function provides a unique way to generate random numbers, making the

random

module a versatile tool for random number generation in Python.

The Importance of Randomness in Programming

Randomness plays a crucial role in many areas of programming. For instance, in game development, randomness can be used to create unpredictable gameplay elements. In data analysis, random sampling can help ensure a representative sample of data. By understanding how to generate random numbers in Python, you can harness the power of randomness in your own programming projects.

Discrete distributions¶

The following function generates a discrete distribution.

random.binomialvariate(n=1, p=0.5)¶

Binomial distribution. Return the number of successes for n independent trials with the probability of success in each trial being p:

Mathematically equivalent to:

sum(random() < p for i in range(n))

The number of trials n should be a non-negative integer. The probability of success p should be between


0.0 <= p <= 1.0

. The result is an integer in the range

0 <= X <= n

.

New in version 3.12.

Random number generator in Python
Random number generator in Python

Sample – Random Numbers

You can also use the sample command to choose several integers from a given range.

By implementing the range command you don’t need to individually write out each number.

from random import sample

numbers = sample(range(1,100) , 5)

print(“Five random numbers between 1 and 100 are:” , *numbers)

Five random numbers between 1 and 100 are: 53 42 11 8 20

Five random numbers between 1 and 100 are: 74 52 51 1 6

Random Samples Task 1 (Frost Comets)

The ice comet from a previous task has broken up into four smaller frosty comets that could pass the Earth anytime from next year to the year 2095.

Print four random years in that range.

Example solutions:

I predict the frost comets will be seen in these years: 2093 2036 2027 2091

I predict the frost comets will be seen in these years: 2076 2033 2053 2085

Random Samples Task 2 (Baby Boy)

Aunt Meredith is having a baby boy.

Create a program that randomly selects 3 male names from a list of 10 possible names.

Example solutions:

Hey Aunt Meredith, how about these names: Charlie Eddie Frank

Hey Aunt Meredith, how about these names: George Harold Bill

Summary

In this tutorial, you discovered how to generate and work with random numbers in Python.

Specifically, you learned:

  • That randomness can be applied in programs via the use of pseudorandom number generators.
  • How to generate random numbers and use randomness via the Python standard library.
  • How to generate arrays of random numbers via the NumPy library.

Do you have any questions?Ask your questions in the comments below and I will do my best to answer.

Why Is \
Why Is \”random.seed()\” So Important In Python?

Importing

Section 5 looks at additional commands that you can import and use from Python’s code libraries.

A library is a collection of different commands that automatically come with Python but are separate from the main file. They can be imported (brought in) to your program by using the import command at the start of your program.

Imagine Python’s library to be similar to an actual library. There are different sections in a real library (such as History, Geography, Reference) and different sections in Python’s library (such as random or time). Each real library has many individual books in each section, just like commands in Python.

randint()

choice()

sample()

shuffle()

random

sleep()

ctime()

strftime()

time

from random import randint

from time import ctime

You can import a specific command from one of Python’s libraries using the from and import commands at the top of your program.

Python3


import


random


beg,end


1000


for


in


range


):


print


(random.randint(beg, end))

Program to Demonstrate the ValueError

In this example, we are seeing that if we passes the floating point values as parameters in the randint() function then a ValueError occurs.

Generate random numbers in Python 🎲
Generate random numbers in Python 🎲

Bookkeeping functions¶

random.seed(a=None, version=2)¶

Initialize the random number generator.

If a is omitted or


None

, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the

os.urandom()

function for details on availability).

If a is an int, it is used directly.

With version 2 (the default), a


str

,

bytes

, or

bytearray

object gets converted to an

int

and all of its bits are used.

With version 1 (provided for reproducing random sequences from older versions of Python), the algorithm for


str

and

bytes

generates a narrower range of seeds.

Changed in version 3.2: Moved to the version 2 scheme which uses all of the bits in a string seed.

random.getstate()¶

Return an object capturing the current internal state of the generator. This object can be passed to


setstate()

to restore the state.

random.setstate(state)¶

state should have been obtained from a previous call to


getstate()

, and

setstate()

restores the internal state of the generator to what it was at the time

getstate()

was called.

What are the Applications of Randint Python Function?

Since the Python randint() function generates a pseudo-random integer, it is usually helpful in gaming and lottery applications. For instance, let’s say a participant gets three chances to guess the following random number generated within a range. If the person gets it correct within the three attempts, he wins, or else loses. Let’s simulate this situation using the randint Python function in the example below.

Example: Creating a Lucky Draw Game with the randint() Function

In the below code, you will generate a random number between 1 and 20 three times. You will then accept input from the user and check if the guess is correct and wins. Let’s begin with our example.

# importing randint function

from random import randint

# Function to generate new random integer

def random_generator():

return randint(1, 20)

# Function to take input from user and show results

def your_guess():

# calling function to generate random numbers

rand_number = random_generator()

# defining the number of

# guesses the user gets

remaining_gus = 3

# Setting win-condition checker flagship variable

flagship = 0

# Using loop to provide only three chances

while remaining_gus > 0:

# Taking user input

guess_num = int(input(“What’s your guess?\n”))

# checking if the guess is correct

if guess_num == rand_number

# setting flagship 1 for correct guess to

# break loop

flagship = 1

break

else:

# printing the failure message

print(“Oops, you missed!”)

# Decrementing guesses left

remaining_gus -= 1

# your_guess function returns True if win-condition

# is satisfied

if flagship == 1:

return True

# else returns False

else:

return False

# Final output code to decide win or lose

if __name__ == ‘__main__’:

if your_guess() is True:

print(“Wow, you hit the bull’s eye!”)

else :

print(“Sorry, better luck next time!”)

Output:

Second attempt output:

Well, as it is evident, you could not get it correct in the first game. But in the second game, you hit the bull’s eye in the very first attempt. Copy-paste the code in any Python compiler, and you too can enjoy the game. You can compete with your friends and family members, and make a day out of it.

Giáo sư Toán dạy bạn đánh Tài Xỉu thắng 100%, quay Gacha bách phát bách trúng
Giáo sư Toán dạy bạn đánh Tài Xỉu thắng 100%, quay Gacha bách phát bách trúng

Using randint in Loops

One of the powerful ways to use

randint()

is within loops. This allows you to generate multiple random numbers at once. For instance, if you need to generate a list of 5 random numbers between 1 and 10, you can use a for loop with

randint()

:


import random random_numbers = [random.randint(1, 10) for _ in range(5)] print(random_numbers) # Output: # (A list of 5 random numbers between 1 and 10)

In this code, we’re using a for loop to generate a list of 5 random numbers. The

random.randint(1, 10)

function is called 5 times, once for each iteration of the loop, generating a new random number each time. The result is a list of 5 random integers.

These examples demonstrate how you can use Python’s

randint()

function in more complex ways to suit your needs. By adjusting the range and using loops, you can generate a variety of random number sequences.

Choice – Random Word

Rather than just numbers, we can also randomly generate characters or strings from a specified range by using the choice command.

You must first import the choice command from the random library. Choice works well with a list of values, which require square brackets and commas separating each word.

Below is a program that randomly chooses from a list of animals:

from random import choice

animals = [“cat” , “dog” , “horse” , “cow”]

print(“A random animal is” , choice(animals))

A random animal is horse

Máy tính có random thật không?
Máy tính có random thật không?

What Happens in Case of Multiple randint() Method Call?

You have seen that when you call the randint Python function; it generates and returns a random integer from the specified range. But what if you call it multiple times? Can it return the same value twice? If not, what happens if the number of calls is more than the available range of values? Let’s get all these queries answered.

Example: Calling the Randint Python Function Multiple Times

In this example, you will keep the available range larger. Let’s see the output.

import random

init=1

end=50

for x in range(5):

print(random.randint(init, end))

Output:

As you can see in the output, the randint() function could still give different random values. Now, let’s cut short the available range and see what happens.

import random

init=1

end=10

for x in range(5):

print(random.randint(init, end))

Output:

Since the range was shorter and the number of calls was still 5, the randint Python function gave a repeated value: 5. Thus, the randint() function can provide the same number twice or even more times. There are also chances that you might get a repeated value, even if the available range is more extensive.

Conclusion

  • randint() function is used to generate the random integers between the two given numbers passed as parameters.
  • Randint is an in-built function of random library in python. So we have to import the random library at the start of our code to generate random numbers.
  • randint function returns:

    • ValueError, when floating point values are passed as parameters.
    • TypeErrorwhen anything other than numeric values is passed as parameters.

The random module in Python allows you to generate pseudo-random variables. The module provides various methods to get the random variables, one of which is the randint method. The randint Python function is a built-in method that lets you generate random integers using the random module.

Python lists, sets, and tuples explained 🍍
Python lists, sets, and tuples explained 🍍

Notes on Reproducibility¶

Sometimes it is useful to be able to reproduce the sequences given by a pseudo-random number generator. By reusing a seed value, the same sequence should be reproducible from run to run as long as multiple threads are not running.

Most of the random module’s algorithms and seeding functions are subject to change across Python versions, but two aspects are guaranteed not to change:

  • If a new seeding method is added, then a backward compatible seeder will be offered.

  • The generator’s


    random()

    method will continue to produce the same sequence when the compatible seeder is given the same seed.

Parameters Used in Randint Python Function

As you can see in the syntax, the Python randint() function accepts two parameters, which are:

  • start: It is a required parameter that accepts integer value and determines the starting range from which it will generate the random integer.
  • end: It is a required parameter that accepts integer value and defines the ending of the range from which it will generate the random integer.
Absolute and Relative imports - Python Tutorial 28
Absolute and Relative imports – Python Tutorial 28

Popular free courses

  • Free Course

    Learn SQL

    In this SQL course, you’ll learn how to manage large datasets and analyze real data using the standard data management language.Beginner friendly,4 LessonsLanguage Fluency

  • Free Course

    Learn JavaScript

    Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.Beginner friendly,11 LessonsLanguage Fluency

  • Free Course

    Learn HTML

    Start at the beginning by learning HTML basics — an important foundation for building and editing web pages.Beginner friendly,6 LessonsLanguage Fluency

The use of randomness is an important part of the configuration and evaluation of machine learning algorithms.

From the random initialization of weights in an artificial neural network, to the splitting of data into random train and test sets, to the random shuffling of a training dataset in stochastic gradient descent, generating random numbers and harnessing randomness is a required skill.

In this tutorial, you will discover how to generate and work with random numbers in Python.

After completing this tutorial, you will know:

  • That randomness can be applied in programs via the use of pseudorandom number generators.
  • How to generate random numbers and use randomness via the Python standard library.
  • How to generate arrays of random numbers via the NumPy library.

Kick-start your project with my new book Statistics for Machine Learning, including step-by-step tutorials and the Python source code files for all examples.

Let’s get started.

How to Generate Random Numbers in PythonPhoto by Thomas Lipike. Some rights reserved.

Answer 55c1f9dbe0a300455c000072

Hi, @Takeshi Travis Sugiyama,


randint

is a function that is part of the

random

module.

The official Python documentation on it is at random.randint(a, b). It returns a pseudorandom integer between and , inclusive.

You must

import

the function in some manner, in order to use it. The statement …


from random import randint

… enables you to use the name

randint

to call the function.

If, instead you had …


import random

… you would need to use dot notation to specify the name of the module, in connection with the name of the function, in order to call it, for example …


return random.randint(0, len(board) - 1)

If you managed to pass without using the

randint

function at all, congratulations :). But, of course the game is less interesting if it does not choose a random location for the battleship.

If you passed with code that used the

randint

function, but after your having removed the

import

statement, it was because Codecademy remembers names defined by previous submissions of exercises in the same section, during a given session. This is a possible source of confusion, as it can cause code to be accepted when it is, in fact, incomplete. To make sure your code is actually valid, you can refresh the page and submit the code again.

Avoiding import loops in Python
Avoiding import loops in Python

Python3


from


random


import


randint


def


generator():


return


randint(


10


def


rand_guess():


random_number


generator()


guess_left


flag


while


guess_left >


guess


int


input


"Pick your number to "


"enter the lucky draw\n"


))


if


guess


random_number:


flag


break


else


print


"Wrong Guess!!"


guess_left


if


flag


is


return


True


else


return


False


if


__name__


'__main__'


if


rand_guess()


is


True


print


"Congrats!! You Win."


else


print


"Sorry, You Lost!"

Output

Pick your number to enter the lucky draw
8
Wrong Guess!!
Pick your number to enter the lucky draw
9
Wrong Guess!!
Pick your number to enter the lucky draw
0
Congrats!! You Win.

Don’t miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology – explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Last Updated :
30 Oct, 2023

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

By Sneh

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this tutorial, we are going to focus on the

randint()

method in Python. In our previous tutorials, we saw different random number generating methods defined inside the random module in our Random Number Tutorial in Python.

So, as you already know, we need to import the random module in Python first to begin using the randint() method. The module essentially creates pseudo-randomness.

Basically, the

randint()

method in Python returns a random integer value between the two lower and higher limits (including both limits) provided as two parameters.

It should be noted that this method is only capable of generating integer-type random value. Take a look at the syntax so that we can further incorporate the method.


#randint() Syntax randint(lower limit , upper limit)

Here,

The above example returns an integer N where N>=beg and N<=end.

It works in the same way

randrange(beg,end)

does, and hence is an alias for the same.

Let us look at the given code below, it illustrates the use and working of the

randint()

method.


import random beg=10 end=100 random_integer = random.randint(beg, end) print("The random integer is :", random_integer)

Output:

Clearly, we can see that the

randint()

method generates a random integer value within the limit 1-100.

Is this value random? What happens when we call the method multiple times? Does it return the same value?

The code snippet below answers all the above-mentioned questions and gives us a clear understanding.


import random beg=10 end=100 for i in range(5): print(random.randint(beg, end))

Output:

For the above code, repeating the

random.randint()

method gives us different random integers for each call within the limit 10 to 100.

Hence, we can infer that the values are random for each call and do not overlap in our case. Furthermore, when the number of calls is large and the range is quite smaller, in that case, the random values generated may collide or overlap.

As said earlier, one must ensure that the higher and lower limit parameters have to be an integer type. For other types, we get a ValueError as shown below.


import random beg=5.3 end=10.2 print(random.randint(beg, end))

Output:


Traceback (most recent call last): File "C:/Users/sneha/Desktop/test.py", line 4, in

print(random.randint(beg, end)) File "C:\Users\sneha\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 222, in randint return self.randrange(a, b+1) File "C:\Users\sneha\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 186, in randrange raise ValueError("non-integer arg 1 for randrange()") ValueError: non-integer arg 1 for randrange() Process finished with exit code 1

I hope this brief tutorial on the randint() method in Python has made the function clear for you. Your feedback is always welcome through the comments.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Click below to sign up and get $200 of credit to try our products over 60 days!

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Using Python’s randint for Random Number Generation

Python’s randint function is a powerful tool in your coding arsenal. It’s like a digital dice, capable of generating random numbers for a variety of applications.

This function can seem a bit confusing at first, but fear not! In this guide, we will dive deep into the ins and outs of using randint in Python. By the end of this guide, you will be able to confidently use the randint function in your own Python projects.

So, let’s roll the dice and start our journey into the world of Python’s randint function.

Pseudorandom Number Generators

The source of randomness that we inject into our programs and algorithms is a mathematical trick called a pseudorandom number generator.

A random number generator is a system that generates random numbers from a true source of randomness. Often something physical, such as a Geiger counter or electrostatic noise, where the results are turned into random numbers. We do not need true randomness in machine learning. Instead we can use pseudorandomness. Pseudorandomness is a sample of numbers that look close to random, but were generated using a deterministic process.

Shuffling data and initializing coefficients with random values use pseudorandom number generators. These little programs are often a function that you can call that will return a random number. Called again, they will return a new random number. Wrapper functions are often also available and allow you to get your randomness as an integer, floating point, within a specific distribution, within a specific range, and so on.

The numbers are generated in a sequence. The sequence is deterministic and is seeded with an initial number. If you do not explicitly seed the pseudorandom number generator, then it may use the current system time in seconds or milliseconds as the seed.

The value of the seed does not matter. Choose anything you wish. What does matter is that the same seeding of the process will result in the same sequence of random numbers.

Let’s make this concrete with some examples.

How To Predict Random Numbers Generated By A Computer
How To Predict Random Numbers Generated By A Computer

Wrapping Up: Python’s randint Function

Python’s

randint()

function is a powerful tool in the

random

module, providing a straightforward way to generate random integers within a specified range. From simple applications to more complex scenarios,

randint()

offers a reliable solution for random number generation.

While

randint()

is generally easy to use, common issues include forgetting to import the

random

module and using incorrect range values. These can be easily avoided by following best practices such as always importing necessary modules and ensuring correct parameter values.

Beyond

randint()

, Python offers other methods for random number generation. These include the

random()

and

uniform()

functions in the

random

module, and the

numpy.random.randint()

function in the NumPy module. Each method has its unique advantages and can be more suitable depending on your specific needs.

Random number generation is a fundamental aspect of programming with diverse applications. By mastering Python’s

randint()

function and understanding other random number generation methods, you can harness the power of randomness in your Python projects.

By Sneh

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

In this tutorial, we are going to focus on the

randint()

method in Python. In our previous tutorials, we saw different random number generating methods defined inside the random module in our Random Number Tutorial in Python.

So, as you already know, we need to import the random module in Python first to begin using the randint() method. The module essentially creates pseudo-randomness.

Basically, the

randint()

method in Python returns a random integer value between the two lower and higher limits (including both limits) provided as two parameters.

It should be noted that this method is only capable of generating integer-type random value. Take a look at the syntax so that we can further incorporate the method.


#randint() Syntax randint(lower limit , upper limit)

Here,

The above example returns an integer N where N>=beg and N<=end.

It works in the same way

randrange(beg,end)

does, and hence is an alias for the same.

Let us look at the given code below, it illustrates the use and working of the

randint()

method.


import random beg=10 end=100 random_integer = random.randint(beg, end) print("The random integer is :", random_integer)

Output:

Clearly, we can see that the

randint()

method generates a random integer value within the limit 1-100.

Is this value random? What happens when we call the method multiple times? Does it return the same value?

The code snippet below answers all the above-mentioned questions and gives us a clear understanding.


import random beg=10 end=100 for i in range(5): print(random.randint(beg, end))

Output:

For the above code, repeating the

random.randint()

method gives us different random integers for each call within the limit 10 to 100.

Hence, we can infer that the values are random for each call and do not overlap in our case. Furthermore, when the number of calls is large and the range is quite smaller, in that case, the random values generated may collide or overlap.

As said earlier, one must ensure that the higher and lower limit parameters have to be an integer type. For other types, we get a ValueError as shown below.


import random beg=5.3 end=10.2 print(random.randint(beg, end))

Output:


Traceback (most recent call last): File "C:/Users/sneha/Desktop/test.py", line 4, in

print(random.randint(beg, end)) File "C:\Users\sneha\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 222, in randint return self.randrange(a, b+1) File "C:\Users\sneha\AppData\Local\Programs\Python\Python37-32\lib\random.py", line 186, in randrange raise ValueError("non-integer arg 1 for randrange()") ValueError: non-integer arg 1 for randrange() Process finished with exit code 1

I hope this brief tutorial on the randint() method in Python has made the function clear for you. Your feedback is always welcome through the comments.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Click below to sign up and get $200 of credit to try our products over 60 days!

Working on improving health and education, reducing inequality, and spurring economic growth? We’d like to help.

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

randint() Function in Python

Alternative Generator¶

class random.Random([seed])¶

Class that implements the default pseudo-random number generator used by the


random

module.

Changed in version 3.11: Formerly the seed could be any hashable object. Now it is limited to:


None

,

int

,

float

,

str

,

bytes

, or

bytearray

.

Subclasses of


Random

should override the following methods if they wish to make use of a different basic generator:

seed(a=None, version=2)¶

Override this method in subclasses to customise the


seed()

behaviour of

Random

instances.

getstate()¶

Override this method in subclasses to customise the


getstate()

behaviour of

Random

instances.

setstate(state)¶

Override this method in subclasses to customise the


setstate()

behaviour of

Random

instances.

random()¶

Override this method in subclasses to customise the


random()

behaviour of

Random

instances.

Optionally, a custom generator subclass can also supply the following method:

getrandbits(k)¶

Override this method in subclasses to customise the


getrandbits()

behaviour of

Random

instances.

class random.SystemRandom([seed])¶

Class that uses the


os.urandom()

function for generating random numbers from sources provided by the operating system. Not available on all systems. Does not rely on software state, and sequences are not reproducible. Accordingly, the

seed()

method has no effect and is ignored. The

getstate()

and

setstate()

methods raise

NotImplementedError

if called.

AVOID Using: \
AVOID Using: \”import *\” At ALL Costs In Python

Expanding the Range of randint

Python’s

randint()

function isn’t limited to small ranges. In fact, you can generate random integers in any range you like. For example, if you’re simulating a lottery draw, you might need to generate numbers between 1 and 1000:


import random lottery_number = random.randint(1, 1000) print(lottery_number) # Output: # (A random number between 1 and 1000)

In this example, we’ve expanded the range of

randint()

to generate a random number between 1 and 1000. This demonstrates the flexibility of the

randint()

function.

What is randint() function in Python?

The randint() function in python is a built-in function of the random module that returns a random integer between the higher and lower limit passed as parameters. The randint() function returns an integer N where N>=beg and N<=end.

We must first import the random module in Python to begin using the randint() function. The module essentially creates pseudo-randomness.

Learn more about random modules from this article.

Fix Python Relative Imports and Auto-completion in VSCode
Fix Python Relative Imports and Auto-completion in VSCode

Functions for integers¶

random.randrange(stop)¶
random.randrange(start, stop[, step])

Return a randomly selected element from


range(start, stop, step)

.

This is roughly equivalent to


choice(range(start, stop, step))

but supports arbitrarily large ranges and is optimized for common cases.

The positional argument pattern matches the


range()

function.

Keyword arguments should not be used because they can be interpreted in unexpected ways. For example


randrange(start=100)

is interpreted as

randrange(0, 100, 1)

.

Changed in version 3.2:


randrange()

is more sophisticated about producing equally distributed values. Formerly it used a style like

int(random()*n)

which could produce slightly uneven distributions.

Changed in version 3.12: Automatic conversion of non-integer types is no longer supported. Calls such as


randrange(10.0)

and

randrange(Fraction(10, 1))

now raise a

TypeError

.

random.randint(a, b)¶

Return a random integer N such that


a <= N <= b

. Alias for

randrange(a, b+1)

.

random.getrandbits(k)¶

Returns a non-negative Python integer with k random bits. This method is supplied with the Mersenne Twister generator and some other generators may also provide it as an optional part of the API. When available,


getrandbits()

enables

randrange()

to handle arbitrarily large ranges.

Changed in version 3.9: This method now accepts zero for k.

Common Issues and Solutions with randint

While using Python’s

randint()

function, you might encounter certain issues. Let’s discuss some common problems and their solutions.

Forgetting to Import the Random Module

One of the most common mistakes is forgetting to import the random module. Without importing it, Python won’t recognize the

randint()

function, leading to an error.


number = randint(1, 10) print(number) # Output: # NameError: name 'randint' is not defined

In this example, we forgot to import the random module, so Python raises a

NameError

because it doesn’t recognize

randint()

. The solution is to import the random module at the beginning of your code.


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

By importing the random module with

import random

, we can now use the

randint()

function without any issues.

Using Incorrect Range Values

Another common mistake is using incorrect values for the range. Remember, the first parameter should be less than or equal to the second. If it’s greater, Python will raise a

ValueError

.


import random number = random.randint(10, 1) print(number) # Output: # ValueError: empty range for randrange() (10,1, -9)

In this example, we tried to generate a random number between 10 and 1, which is an empty range. The solution is to ensure the first parameter is less than or equal to the second.

3 Ways to Make a Custom AI Assistant | RAG, Tools, & Fine-tuning
3 Ways to Make a Custom AI Assistant | RAG, Tools, & Fine-tuning

Summary

In this tutorial, you discovered how to generate and work with random numbers in Python.

Specifically, you learned:

  • That randomness can be applied in programs via the use of pseudorandom number generators.
  • How to generate random numbers and use randomness via the Python standard library.
  • How to generate arrays of random numbers via the NumPy library.

Do you have any questions?Ask your questions in the comments below and I will do my best to answer.

Python Random randint() Method

Example

Return a number between 3 and 9 (both included):

import randomprint(random.randint(3, 9))

Try it Yourself »

print(random.randint(3, 9))

Random Numbers with the Python Standard Library

The Python standard library provides a module called random that offers a suite of functions for generating random numbers.

Python uses a popular and robust pseudorandom number generator called the Mersenne Twister.

In this section, we will look at a number of use cases for generating and using random numbers and randomness with the standard Python API.

Need help with Statistics for Machine Learning?

Take my free 7-day email crash course now (with sample code).

Click to sign-up and also get a free PDF Ebook version of the course.

Seed The Random Number Generator

The pseudorandom number generator is a mathematical function that generates a sequence of nearly random numbers.

It takes a parameter to start off the sequence, called the seed. The function is deterministic, meaning given the same seed, it will produce the same sequence of numbers every time. The choice of seed does not matter.

The seed() function will seed the pseudorandom number generator, taking an integer value as an argument, such as 1 or 7. If the seed() function is not called prior to using randomness, the default is to use the current system time in milliseconds from epoch (1970).

The example below demonstrates seeding the pseudorandom number generator, generates some random numbers, and shows that reseeding the generator will result in the same sequence of numbers being generated.

10

11

# seed the pseudorandom number generator

from random import seed

from random import random

# seed random number generator

seed(1)

# generate some random numbers

print(random(), random(), random())

# reset the seed

seed(1)

# generate some random numbers

print(random(), random(), random())

Running the example seeds the pseudorandom number generator with the value 1, generates 3 random numbers, reseeds the generator, and shows that the same three random numbers are generated.

0.13436424411240122 0.8474337369372327 0.763774618976614

0.13436424411240122 0.8474337369372327 0.763774618976614

It can be useful to control the randomness by setting the seed to ensure that your code produces the same result each time, such as in a production model.

For running experiments where randomization is used to control for confounding variables, a different seed may be used for each experimental run.

Random Floating Point Values

Random floating point values can be generated using the random() function. Values will be generated in the range between 0 and 1, specifically in the interval [0,1).

Values are drawn from a uniform distribution, meaning each value has an equal chance of being drawn.

The example below generates 10 random floating point values.

# generate random floating point values

from random import seed

from random import random

# seed random number generator

seed(1)

# generate random numbers between 0-1

for _ in range(10):

value = random()

print(value)

Running the example generates and prints each random floating point value.

10

0.13436424411240122

0.8474337369372327

0.763774618976614

0.2550690257394217

0.49543508709194095

0.4494910647887381

0.651592972722763

0.7887233511355132

0.0938595867742349

0.02834747652200631

The floating point values could be rescaled to a desired range by multiplying them by the size of the new range and adding the min value, as follows:

scaled value = min + (value * (max – min))

Where min and max are the minimum and maximum values of the desired range respectively, and value is the randomly generated floating point value in the range between 0 and 1.

Random Integer Values

Random integer values can be generated with the randint() function.

This function takes two arguments: the start and the end of the range for the generated integer values. Random integers are generated within and including the start and end of range values, specifically in the interval [start, end]. Random values are drawn from a uniform distribution.

The example below generates 10 random integer values between 0 and 10.

# generate random integer values

from random import seed

from random import randint

# seed random number generator

seed(1)

# generate some integers

for _ in range(10):

value = randint(0, 10)

print(value)

Running the example generates and prints 10 random integer values.

10

10

Random Gaussian Values

Random floating point values can be drawn from a Gaussian distribution using the gauss() function.

This function takes two arguments that correspond to the parameters that control the size of the distribution, specifically the mean and the standard deviation.

The example below generates 10 random values drawn from a Gaussian distribution with a mean of 0.0 and a standard deviation of 1.0.

Note that these parameters are not the bounds on the values and that the spread of the values will be controlled by the bell shape of the distribution, in this case proportionately likely above and below 0.0.

# generate random Gaussian values

from random import seed

from random import gauss

# seed random number generator

seed(1)

# generate some Gaussian values

for _ in range(10):

value = gauss(0, 1)

print(value)

Running the example generates and prints 10 Gaussian random values.

10

1.2881847531554629

1.449445608699771

0.06633580893826191

-0.7645436509716318

-1.0921732151041414

0.03133451683171687

-1.022103170010873

-1.4368294451025299

0.19931197648375384

0.13337460465860485

Note: In the random module, there is a function

normalvariate()

that functions the same as

gauss()

. The former is thread-safe while

gauss()

is not. However, you rarely run Python in multithread and

gauss()

is faster.

Randomly Choosing From a List

Random numbers can be used to randomly choose an item from a list.

For example, if a list had 10 items with indexes between 0 and 9, then you could generate a random integer between 0 and 9 and use it to randomly select an item from the list. The choice() function implements this behavior for you. Selections are made with a uniform likelihood.

The example below generates a list of 20 integers and gives five examples of choosing one random item from the list.

10

11

12

# choose a random element from a list

from random import seed

from random import choice

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# make choices from the sequence

for _ in range(5):

selection = choice(sequence)

print(selection)

Running the example first prints the list of integer values, followed by five examples of choosing and printing a random value from the list.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

18

Random Subsample From a List

We may be interested in repeating the random selection of items from a list to create a randomly chosen subset.

Importantly, once an item is selected from the list and added to the subset, it should not be added again. This is called selection without replacement because once an item from the list is selected for the subset, it is not added back to the original list (i.e. is not made available for re-selection).

This behavior is provided in the sample() function that selects a random sample from a list without replacement. The function takes both the list and the size of the subset to select as arguments. Note that items are not actually removed from the original list, only selected into a copy of the list.

The example below demonstrates selecting a subset of five items from a list of 20 integers.

10

11

# select a random sample without replacement

from random import seed

from random import sample

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# select a subset without replacement

subset = sample(sequence, 5)

print(subset)

Running the example first prints the list of integer values, then the random sample is chosen and printed for comparison.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[4, 18, 2, 8, 3]

Randomly Shuffle a List

Randomness can be used to shuffle a list of items, like shuffling a deck of cards.

The shuffle() function can be used to shuffle a list. The shuffle is performed in place, meaning that the list provided as an argument to the shuffle() function is shuffled rather than a shuffled copy of the list being made and returned.

The example below demonstrates randomly shuffling a list of integer values.

10

11

# randomly shuffle a sequence

from random import seed

from random import shuffle

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# randomly shuffle the sequence

shuffle(sequence)

print(sequence)

Running the example first prints the list of integers, then the same list after it has been randomly shuffled.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[11, 5, 17, 19, 9, 0, 16, 1, 15, 6, 10, 13, 14, 12, 7, 3, 8, 2, 18, 4]

Cập Nhật | MEME Lend, ZetaChain, B² Network, Near Wallet, KuScription, XPLA
Cập Nhật | MEME Lend, ZetaChain, B² Network, Near Wallet, KuScription, XPLA

Sample – Random Strings

To choose more than one value from a set of data, use the sample command.

Sample is used with a list of values and a number representing how many from that list to pick. The code sample(days,2) picks two random values from the list called days.

Both examples below perform the same task but, as with most code, there is no one way to solve a problem.

from random import sample

days = [“Monday” , “Tuesday” , “Wednesday” , “Thursday” , “Friday”]two_days = sample(days , 2)

print(“You will be set homework on:” , *two_days)

A separate list and then a sample.

You will be set homework on: Thursday Monday

You will be set homework on: Friday Tuesday

from random import sample

two_days = sample([“Monday” , “Tuesday” , “Wednesday” , “Thursday” , “Friday”] , 2)

print(“You will be set homework on:” , *two_days)

The list and sample is combined on one line.

The sample command actually makes a new list with the number of values selected (e.g. [“Tuesday” , “Thursday”] in the examples above).

You can use an asterisk – * – directly before the sampled variable to print just the list values, otherwise the brackets and apostrophes will be printed too.

from random import sample

names = sample([“Bob” , “Ben” , “Jen” , “Ken”] , 2)

print(“The names are:” , names)

from random import sample

names = sample([“Bob” , “Ben” , “Jen” , “Ken”] , 2)

print(“The names are:” , *names)

The names are: [‘Bob’, ‘Jen’]

The names are: Bob Jen

Exploring Alternatives to randint

While

randint()

is a powerful tool for generating random integers, Python offers other functions and modules for random number generation. These include the

random()

function, the

uniform()

function, and the NumPy module.

The random Function

The

random()

function is another part of Python’s random module. Unlike

randint()

,

random()

generates a random floating-point number between 0.0 and 1.0.


import random random_number = random.random() print(random_number) # Output: # (A random floating-point number between 0.0 and 1.0)

The

random()

function doesn’t take any arguments and returns a random float in the range [0.0, 1.0).

The uniform Function

The

uniform(a, b)

function generates a random floating-point number between and . It’s similar to

randint()

, but it works with floating-point numbers.


import random random_number = random.uniform(1.0, 10.0) print(random_number) # Output: # (A random floating-point number between 1.0 and 10.0)

In this example,

random.uniform(1.0, 10.0)

generates a random float between 1.0 and 10.0.

The NumPy Module

NumPy, a powerful library for numerical computation in Python, also provides functions for random number generation. For instance,

numpy.random.randint()

generates random integers in a similar way to Python’s

randint()

.


import numpy random_number = numpy.random.randint(1, 10) print(random_number) # Output: # (A random integer between 1 and 10)

In this example,

numpy.random.randint(1, 10)

generates a random integer between 1 and 10, just like Python’s

randint()

function.

These alternative methods offer more flexibility and options for random number generation in Python. Depending on your specific needs, you might find one of these methods more suitable than

randint()

.

Python randint() function | random module | Amit Thinks
Python randint() function | random module | Amit Thinks

Parameter Values

Parameter Description
start Required. An integer specifying at which position to start.
stop Required. An integer specifying at which position to end.

random — Generate pseudo-random numbers¶

Source code: Lib/random.py

This module implements pseudo-random number generators for various distributions.

For integers, there is uniform selection from a range. For sequences, there is uniform selection of a random element, a function to generate a random permutation of a list in-place, and a function for random sampling without replacement.

On the real line, there are functions to compute uniform, normal (Gaussian), lognormal, negative exponential, gamma, and beta distributions. For generating distributions of angles, the von Mises distribution is available.

Almost all module functions depend on the basic function

random()

, which
generates a random float uniformly in the half-open range

0.0 <= X < 1.0

.
Python uses the Mersenne Twister as the core generator. It produces 53-bit precision
floats and has a period of 2**19937-1. The underlying implementation in C is
both fast and threadsafe. The Mersenne Twister is one of the most extensively
tested random number generators in existence. However, being completely
deterministic, it is not suitable for all purposes, and is completely unsuitable
for cryptographic purposes.

The functions supplied by this module are actually bound methods of a hidden
instance of the

random.Random

class. You can instantiate your own
instances of

Random

to get generators that don’t share state.

Class

Random

can also be subclassed if you want to use a different
basic generator of your own devising: see the documentation on that class for
more details.

The

random

module also provides the

SystemRandom

class which
uses the system function

os.urandom()

to generate random numbers
from sources provided by the operating system.

Warning

The pseudo-random generators of this module should not be used for
security purposes. For security or cryptographic uses, see the

secrets

module.

See also

M. Matsumoto and T. Nishimura, “Mersenne Twister: A 623-dimensionally equidistributed uniform pseudorandom number generator”, ACM Transactions on Modeling and Computer Simulation Vol. 8, No. 1, January pp.3–30 1998.

Complementary-Multiply-with-Carry recipe for a compatible alternative random number generator with a long period and comparatively simple update operations.

Parameters of randint() function in python

randint() function in Python includes two parameters:

  • start parameter, which is the starting point from and including which the random integer would be generated,
  • end parameter, which is the ending point up to which the function would return the random integer.

Both start and end must be integer type values.

Python random numbers 🎲
Python random numbers 🎲

Pseudorandom Number Generators

The source of randomness that we inject into our programs and algorithms is a mathematical trick called a pseudorandom number generator.

A random number generator is a system that generates random numbers from a true source of randomness. Often something physical, such as a Geiger counter or electrostatic noise, where the results are turned into random numbers. We do not need true randomness in machine learning. Instead we can use pseudorandomness. Pseudorandomness is a sample of numbers that look close to random, but were generated using a deterministic process.

Shuffling data and initializing coefficients with random values use pseudorandom number generators. These little programs are often a function that you can call that will return a random number. Called again, they will return a new random number. Wrapper functions are often also available and allow you to get your randomness as an integer, floating point, within a specific distribution, within a specific range, and so on.

The numbers are generated in a sequence. The sequence is deterministic and is seeded with an initial number. If you do not explicitly seed the pseudorandom number generator, then it may use the current system time in seconds or milliseconds as the seed.

The value of the seed does not matter. Choose anything you wish. What does matter is that the same seeding of the process will result in the same sequence of random numbers.

Let’s make this concrete with some examples.

Common Issues and Solutions with randint

While using Python’s

randint()

function, you might encounter certain issues. Let’s discuss some common problems and their solutions.

Forgetting to Import the Random Module

One of the most common mistakes is forgetting to import the random module. Without importing it, Python won’t recognize the

randint()

function, leading to an error.


number = randint(1, 10) print(number) # Output: # NameError: name 'randint' is not defined

In this example, we forgot to import the random module, so Python raises a

NameError

because it doesn’t recognize

randint()

. The solution is to import the random module at the beginning of your code.


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

By importing the random module with

import random

, we can now use the

randint()

function without any issues.

Using Incorrect Range Values

Another common mistake is using incorrect values for the range. Remember, the first parameter should be less than or equal to the second. If it’s greater, Python will raise a

ValueError

.


import random number = random.randint(10, 1) print(number) # Output: # ValueError: empty range for randrange() (10,1, -9)

In this example, we tried to generate a random number between 10 and 1, which is an empty range. The solution is to ensure the first parameter is less than or equal to the second.

What is Random RandRange in Python?
What is Random RandRange in Python?

Real-World Applications of Python’s randint

Python’s

randint()

function isn’t just for academic exercises—it has practical applications in real-world scenarios. Let’s explore some of these applications.

Simulations

In simulations,

randint()

can be used to generate random inputs. For example, in a weather simulation,

randint()

could generate random temperatures or wind speeds.


import random random_temperature = random.randint(-10, 40) print('Random Temperature:', random_temperature, '°C') # Output: # Random Temperature: (A random number between -10 and 40) °C

In this code, we’re using

randint()

to generate a random temperature between -10 and 40 degrees Celsius.

Games

In games,

randint()

can be used to create unpredictable elements, making the game more exciting. For instance, in a dice game,

randint()

could be used to generate the dice roll.


import random dice_roll = random.randint(1, 6) print('Dice Roll:', dice_roll) # Output: # Dice Roll: (A random number between 1 and 6)

In this code, we’re using

randint()

to simulate a dice roll, generating a random number between 1 and 6.

Data Analysis

In data analysis,

randint()

can be used to generate random samples from a larger dataset. This can ensure a more representative sample and more accurate analysis.

Choice – Random Character

Instead of using a list you can randomly select a character from a string.

The program below randomly selects a character from the variable named ‘letters’ which is the alphabet.

from random import choice

letters = “abcdefghijklmnopqrstuvwxyz”

print(“A random letter is” , choice(letters))

A random letter is e

A random letter is y

Random Choice Task 1 (Holiday Destinations)

Harriet can’t decide where to go on holiday and needs help deciding.

Make a list of at least 6 destinations (see the animal example above) and use the choice command (don’t forget to import it from the random library) to print a random destination.

Example solutions:

Why don’t you go to Paris on holiday?

Why don’t you go to Barcelona on holiday?

Random Choice Task 2 (Vowels)

Use the choice command to randomly select a vowel (look at the alphabet example above).

Ask the user to input a vowel and use an if statement to check if the user’s letter matches the randomly selected letter.

Print a suitable statement if they match and something else if they don’t.

Example solutions:

Enter a vowel: iRandom vowel: iThe vowels matched!

Enter a vowel: oRandom vowel: uThe vowels didn’t match!

Numpy Random ALL EXPLAINED!!!
Numpy Random ALL EXPLAINED!!!

Real-valued distributions¶

The following functions generate specific real-valued distributions. Function parameters are named after the corresponding variables in the distribution’s equation, as used in common mathematical practice; most of these equations can be found in any statistics text.

random.random()¶

Return the next random floating point number in the range


0.0 <= X < 1.0

random.uniform(a, b)¶

Return a random floating point number N such that


a <= N <= b

for

a <= b

and

b <= N <= a

for

b < a

.

The end-point value

may or may not be included in the range depending on floating-point rounding in the equation

a + (b-a) * random()

.

random.triangular(low, high, mode)¶

Return a random floating point number N such that


low <= N <= high

and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.

random.betavariate(alpha, beta)¶

Beta distribution. Conditions on the parameters are


alpha > 0

and

beta > 0

. Returned values range between 0 and 1.

random.expovariate(lambd=1.0)¶

Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.

Changed in version 3.12: Added the default value for


lambd

.

random.gammavariate(alpha, beta)¶

Gamma distribution. (Not the gamma function!) The shape and scale parameters, alpha and beta, must have positive values. (Calling conventions vary and some sources define ‘beta’ as the inverse of the scale).

The probability distribution function is:

x ** (alpha – 1) * math.exp(-x / beta) pdf(x) = ————————————– math.gamma(alpha) * beta ** alpha

random.gauss(mu=0.0, sigma=1.0)¶

Normal distribution, also called the Gaussian distribution. mu is the mean, and sigma is the standard deviation. This is slightly faster than the


normalvariate()

function defined below.

Multithreading note: When two threads call this function simultaneously, it is possible that they will receive the same return value. This can be avoided in three ways. 1) Have each thread use a different instance of the random number generator. 2) Put locks around all calls. 3) Use the slower, but thread-safe


normalvariate()

function instead.

Changed in version 3.11: mu and sigma now have default arguments.

random.lognormvariate(mu, sigma)¶

Log normal distribution. If you take the natural logarithm of this distribution, you’ll get a normal distribution with mean mu and standard deviation sigma. mu can have any value, and sigma must be greater than zero.

random.normalvariate(mu=0.0, sigma=1.0)¶

Normal distribution. mu is the mean, and sigma is the standard deviation.

Changed in version 3.11: mu and sigma now have default arguments.

random.vonmisesvariate(mu, kappa)¶

mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi.

random.paretovariate(alpha)¶

Pareto distribution. alpha is the shape parameter.

random.weibullvariate(alpha, beta)¶

Weibull distribution. alpha is the scale parameter and beta is the shape parameter.

More Examples

Example 1: Working of randint() function

Code:

Output:

Explanation: The above program generates a random integer using the randint() function in python in 3 different cases that include

  • Case 1: Generates a random number between two positive integers
  • Case 2: Generates a random number between two negative integers.
  • Case 3: Generates a random number between one positive and other negative integer.

Example 2: ValueError in randint() function

Code:

Output:

Explanation:

The above program demonstrates how we can get ValueError while using randint() function in python. We get this error because we passed floating point values as parameters in the randint() function.

Example 3: TypeError in randint() function

Code:

Output:

Explanation: The above program demonstrates how we can get TypeError while using randint() function in python. We got this error because we passed string or character literals that are non-numeric values as parameters in the randint() function.

Click Here, To know about the int() function in python.

Python for Beginners: 12. Random Module in Python (random | randint | choice | shuffle | sample)
Python for Beginners: 12. Random Module in Python (random | randint | choice | shuffle | sample)

Python randint() Method Syntax

Syntax: randint(start, end)

Parameters :

(start, end) : Both of them must be integer type values.

Returns :

A random integer in range [start, end] including the end points.

Errors and Exceptions :

ValueError : Returns a ValueError when floating point values are passed as parameters.

TypeError : Returns a TypeError when anything other than numeric values are passed as parameters.

How randint() in Python work?

In this example, we are using the randint() method in Python to find a random number in a given range.

Understanding Python’s randint Function

Python’s

randint()

is a function that belongs to the

random

module. It is used to generate a random integer within a defined range. The function takes two parameters: the start and end of the range, inclusive.

Using randint: A Simple Example

Let’s look at a simple code example to understand how

randint()

works:


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

In this example,

import random

is used to import the random module, which contains the randint function. Next,

random.randint(1, 10)

is used to generate a random integer between 1 and 10, inclusive. The result is then stored in the variable

number

, which is printed out.

Parameters and Return Value

The

randint(a, b)

function takes two parameters:

  • : The lower limit of the range (inclusive).
  • : The upper limit of the range (inclusive).

The function returns a random integer such that

a <= N <= b

.

Understanding the Output

The output of the

randint()

function is a random integer within the specified range. In our example, the output is a random number between 1 and 10. Each time you run the code, you might get a different number because the selection is random.

By understanding the basics of Python’s

randint()

function, you can start to harness the power of random number generation in your coding projects.

Sıfırdan Python Dersleri Ders 12: Random modülü
Sıfırdan Python Dersleri Ders 12: Random modülü

Functions for sequences¶

random.choice(seq)¶

Return a random element from the non-empty sequence seq. If seq is empty, raises


IndexError

.

random.choices(population, weights=None, *, cum_weights=None, k=1)¶

Return a k sized list of elements chosen from the population with replacement. If the population is empty, raises


IndexError

.

If a weights sequence is specified, selections are made according to the relative weights. Alternatively, if a cum_weights sequence is given, the selections are made according to the cumulative weights (perhaps computed using


itertools.accumulate()

). For example, the relative weights

[10, 5, 30, 5]

are equivalent to the cumulative weights

[10, 15, 45, 50]

. Internally, the relative weights are converted to cumulative weights before making selections, so supplying the cumulative weights saves work.

If neither weights nor cum_weights are specified, selections are made with equal probability. If a weights sequence is supplied, it must be the same length as the population sequence. It is a


TypeError

to specify both weights and cum_weights.

The weights or cum_weights can use any numeric type that interoperates with the


float

values returned by

random()

(that includes integers, floats, and fractions but excludes decimals). Weights are assumed to be non-negative and finite. A

ValueError

is raised if all weights are zero.

For a given seed, the


choices()

function with equal weighting typically produces a different sequence than repeated calls to

choice()

. The algorithm used by

choices()

uses floating point arithmetic for internal consistency and speed. The algorithm used by

choice()

defaults to integer arithmetic with repeated selections to avoid small biases from round-off error.

New in version 3.6.

Changed in version 3.9: Raises a


ValueError

if all weights are zero.

random.shuffle(x)¶

Shuffle the sequence x in place.

To shuffle an immutable sequence and return a new shuffled list, use


sample(x, k=len(x))

instead.

Note that even for small


len(x)

, the total number of permutations of x can quickly grow larger than the period of most random number generators. This implies that most permutations of a long sequence can never be generated. For example, a sequence of length 2080 is the largest that can fit within the period of the Mersenne Twister random number generator.

Changed in version 3.11: Removed the optional parameter random.

random.sample(population, k, *, counts=None)¶

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Returns a new list containing elements from the population while leaving the original population unchanged. The resulting list is in selection order so that all sub-slices will also be valid random samples. This allows raffle winners (the sample) to be partitioned into grand prize and second place winners (the subslices).

Members of the population need not be hashable or unique. If the population contains repeats, then each occurrence is a possible selection in the sample.

Repeated elements can be specified one at a time or with the optional keyword-only counts parameter. For example,


sample(['red', 'blue'], counts=[4, 2], k=5)

is equivalent to

sample(['red', 'red', 'red', 'red', 'blue', 'blue'], k=5)

.

To choose a sample from a range of integers, use a


range()

object as an argument. This is especially fast and space efficient for sampling from a large population:

sample(range(10000000), k=60)

.

If the sample size is larger than the population size, a


ValueError

is raised.

Changed in version 3.9: Added the counts parameter.

Changed in version 3.11: The population must be a sequence. Automatic conversion of sets to lists is no longer supported.

Using randint in Loops

One of the powerful ways to use

randint()

is within loops. This allows you to generate multiple random numbers at once. For instance, if you need to generate a list of 5 random numbers between 1 and 10, you can use a for loop with

randint()

:


import random random_numbers = [random.randint(1, 10) for _ in range(5)] print(random_numbers) # Output: # (A list of 5 random numbers between 1 and 10)

In this code, we’re using a for loop to generate a list of 5 random numbers. The

random.randint(1, 10)

function is called 5 times, once for each iteration of the loop, generating a new random number each time. The result is a list of 5 random integers.

These examples demonstrate how you can use Python’s

randint()

function in more complex ways to suit your needs. By adjusting the range and using loops, you can generate a variety of random number sequences.

Bai19: Hàm lấy số ngẫu nhiên - random python - Tự học lập trình python
Bai19: Hàm lấy số ngẫu nhiên – random python – Tự học lập trình python

Exploring Alternatives to randint

While

randint()

is a powerful tool for generating random integers, Python offers other functions and modules for random number generation. These include the

random()

function, the

uniform()

function, and the NumPy module.

The random Function

The

random()

function is another part of Python’s random module. Unlike

randint()

,

random()

generates a random floating-point number between 0.0 and 1.0.


import random random_number = random.random() print(random_number) # Output: # (A random floating-point number between 0.0 and 1.0)

The

random()

function doesn’t take any arguments and returns a random float in the range [0.0, 1.0).

The uniform Function

The

uniform(a, b)

function generates a random floating-point number between and . It’s similar to

randint()

, but it works with floating-point numbers.


import random random_number = random.uniform(1.0, 10.0) print(random_number) # Output: # (A random floating-point number between 1.0 and 10.0)

In this example,

random.uniform(1.0, 10.0)

generates a random float between 1.0 and 10.0.

The NumPy Module

NumPy, a powerful library for numerical computation in Python, also provides functions for random number generation. For instance,

numpy.random.randint()

generates random integers in a similar way to Python’s

randint()

.


import numpy random_number = numpy.random.randint(1, 10) print(random_number) # Output: # (A random integer between 1 and 10)

In this example,

numpy.random.randint(1, 10)

generates a random integer between 1 and 10, just like Python’s

randint()

function.

These alternative methods offer more flexibility and options for random number generation in Python. Depending on your specific needs, you might find one of these methods more suitable than

randint()

.

Return Value of the Python randint() Function

The randint Python function returns a randomly generated integer from the specified range, with both inclusive parameters.

Example: Demonstrating the Use of Randint Python Function

# importing the random module

import random

# using the randint function

int1 = random.randint(0, 5)

print(“Random number generated between 0 and 5 using the randint() function is % s” % (int1))

Output:

Here, you need to first import the random module in the above code, and then use the randint Python function to generate a random integer from 0 to 5.

Note: Your output may vary as a random integer is selected and returned by the randint() function.

How To Generate Random Numbers In Python
How To Generate Random Numbers In Python

What Errors and Exceptions Can Occur While Using Randint in Python?

The Python randint() function can throw the following two errors:

  • ValueError: This error is thrown if you try to pass floating-point numbers as arguments
  • TypeError: This error is thrown if you try to pass anything except numeric values as arguments

Example: Getting ValueError for Randint Python Function

In the code below, you will try passing a floating-point value as a parameter to get the ValueError while compiling the program.

# importing the random module

import random

# using the randint function

int1 = random.randint(0.0, 4.9)

print(int1)

Output:

As you passed a floating-point value as the second (end) parameter, you got a ValueError while running the code.

Example: Getting TypeError for Randint Python Function

In the code below, you will try passing a string value as a parameter to get the TypeError while compiling the program intentionally.

# importing the random module

import random

# using the randint function

int1 = random.randint(‘x’, ‘y’)

print(int1)

Output:

As you can see in the output, this demo got a TypeError saying ‘can only concatenate str (not “int”) to str’ as you passed string values instead of integers.

Recipes¶

These recipes show how to efficiently make random selections
from the combinatoric iterators in the

itertools

module:

def random_product(*args, repeat=1): “Random selection from itertools.product(*args, **kwds)” pools = [tuple(pool) for pool in args] * repeat return tuple(map(random.choice, pools)) def random_permutation(iterable, r=None): “Random selection from itertools.permutations(iterable, r)” pool = tuple(iterable) r = len(pool) if r is None else r return tuple(random.sample(pool, r)) def random_combination(iterable, r): “Random selection from itertools.combinations(iterable, r)” pool = tuple(iterable) n = len(pool) indices = sorted(random.sample(range(n), r)) return tuple(pool[i] for i in indices) def random_combination_with_replacement(iterable, r): “Choose r elements with replacement. Order the result to match the iterable.” # Result will be in set(itertools.combinations_with_replacement(iterable, r)). pool = tuple(iterable) n = len(pool) indices = sorted(random.choices(range(n), k=r)) return tuple(pool[i] for i in indices)

The default

random()

returns multiples of 2⁻⁵³ in the range
0.0 ≤ x < 1.0. All such numbers are evenly spaced and are exactly
representable as Python floats. However, many other representable
floats in that interval are not possible selections. For example,

0.05954861408025609

isn’t an integer multiple of 2⁻⁵³.

The following recipe takes a different approach. All floats in the interval are possible selections. The mantissa comes from a uniform distribution of integers in the range 2⁵² ≤ mantissa < 2⁵³. The exponent comes from a geometric distribution where exponents smaller than -53 occur half as often as the next larger exponent.

from random import Random from math import ldexp class FullRandom(Random): def random(self): mantissa = 0x10_0000_0000_0000 | self.getrandbits(52) exponent = -53 x = 0 while not x: x = self.getrandbits(32) exponent += x.bit_length() – 32 return ldexp(mantissa, exponent)

All real valued distributions in the class will use the new method:

>>> fr = FullRandom() >>> fr.random() 0.05954861408025609 >>> fr.expovariate(0.25) 8.87925541791544

The recipe is conceptually equivalent to an algorithm that chooses from
all the multiples of 2⁻¹⁰⁷⁴ in the range 0.0 ≤ x < 1.0. All such
numbers are evenly spaced, but most have to be rounded down to the
nearest representable Python float. (The value 2⁻¹⁰⁷⁴ is the smallest
positive unnormalized float and is equal to

math.ulp(0.0)

.)

See also

Generating Pseudo-random Floating-Point Values a
paper by Allen B. Downey describing ways to generate more
fine-grained floats than normally generated by

random()

.

Using Python’s randint for Random Number Generation

Python’s randint function is a powerful tool in your coding arsenal. It’s like a digital dice, capable of generating random numbers for a variety of applications.

This function can seem a bit confusing at first, but fear not! In this guide, we will dive deep into the ins and outs of using randint in Python. By the end of this guide, you will be able to confidently use the randint function in your own Python projects.

So, let’s roll the dice and start our journey into the world of Python’s randint function.

Python Random Randint
Python Random Randint

Random Numbers with NumPy

In machine learning, you are likely using libraries such as scikit-learn and Keras.

These libraries make use of NumPy under the covers, a library that makes working with vectors and matrices of numbers very efficient.

NumPy also has its own implementation of a pseudorandom number generator and convenience wrapper functions.

NumPy also implements the Mersenne Twister pseudorandom number generator.

Let’s look at a few examples of generating random numbers and using randomness with NumPy arrays.

Seed The Random Number Generator

The NumPy pseudorandom number generator is different from the Python standard library pseudorandom number generator.

Importantly, seeding the Python pseudorandom number generator does not impact the NumPy pseudorandom number generator. It must be seeded and used separately.

The seed() function can be used to seed the NumPy pseudorandom number generator, taking an integer as the seed value.

The example below demonstrates how to seed the generator and how reseeding the generator will result in the same sequence of random numbers being generated.

10

11

# seed the pseudorandom number generator

from numpy.random import seed

from numpy.random import rand

# seed random number generator

seed(1)

# generate some random numbers

print(rand(3))

# reset the seed

seed(1)

# generate some random numbers

print(rand(3))

Running the example seeds the pseudorandom number generator, prints a sequence of random numbers, then reseeds the generator showing that the exact same sequence of random numbers is generated.

[4.17022005e-01 7.20324493e-01 1.14374817e-04]

[4.17022005e-01 7.20324493e-01 1.14374817e-04]

Array of Random Floating Point Values

An array of random floating point values can be generated with the rand() NumPy function.

If no argument is provided, then a single random value is created, otherwise the size of the array can be specified.

The example below creates an array of 10 random floating point values drawn from a uniform distribution.

# generate random floating point values

from numpy.random import seed

from numpy.random import rand

# seed random number generator

seed(1)

# generate random numbers between 0-1

values = rand(10)

print(values)

Running the example generates and prints the NumPy array of random floating point values.

[4.17022005e-01 7.20324493e-01 1.14374817e-04 3.02332573e-01

1.46755891e-01 9.23385948e-02 1.86260211e-01 3.45560727e-01

3.96767474e-01 5.38816734e-01]

Array of Random Integer Values

An array of random integers can be generated using the randint() NumPy function.

This function takes three arguments, the lower end of the range, the upper end of the range, and the number of integer values to generate or the size of the array. Random integers will be drawn from a uniform distribution including the lower value and excluding the upper value, e.g. in the interval [lower, upper).

The example below demonstrates generating an array of random integers.

# generate random integer values

from numpy.random import seed

from numpy.random import randint

# seed random number generator

seed(1)

# generate some integers

values = randint(0, 10, 20)

print(values)

Running the example generates and prints an array of 20 random integer values between 0 and 10.

[5 8 9 5 0 0 1 7 6 9 2 4 5 2 4 2 4 7 7 9]

Array of Random Gaussian Values

An array of random Gaussian values can be generated using the randn() NumPy function.

This function takes a single argument to specify the size of the resulting array. The Gaussian values are drawn from a standard Gaussian distribution; this is a distribution that has a mean of 0.0 and a standard deviation of 1.0.

The example below shows how to generate an array of random Gaussian values.

# generate random Gaussian values

from numpy.random import seed

from numpy.random import randn

# seed random number generator

seed(1)

# generate some Gaussian values

values = randn(10)

print(values)

Running the example generates and prints an array of 10 random values from a standard Gaussian distribution.

[ 1.62434536 -0.61175641 -0.52817175 -1.07296862 0.86540763 -2.3015387

1.74481176 -0.7612069 0.3190391 -0.24937038]

Values from a standard Gaussian distribution can be scaled by multiplying the value by the standard deviation and adding the mean from the desired scaled distribution. For example:

scaled value = mean + value * stdev

Where mean and stdev are the mean and standard deviation for the desired scaled Gaussian distribution and value is the randomly generated value from a standard Gaussian distribution.

Shuffle NumPy Array

A NumPy array can be randomly shuffled in-place using the shuffle() NumPy function.

The example below demonstrates how to shuffle a NumPy array.

10

11

# randomly shuffle a sequence

from numpy.random import seed

from numpy.random import shuffle

# seed random number generator

seed(1)

# prepare a sequence

sequence = [i for i in range(20)]

print(sequence)

# randomly shuffle the sequence

shuffle(sequence)

print(sequence)

Running the example first generates a list of 20 integer values, then shuffles and prints the shuffled array.

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

[3, 16, 6, 10, 2, 14, 4, 17, 7, 1, 13, 0, 19, 18, 9, 15, 8, 12, 11, 5]

Modern Ways of Random Number Generation in NumPy

In newer version of NumPy, you can do random number generation the following way:

10

11

12

13

14

15

16

import numpy as np

rng = np.random.Generator(np.random.PCG64())

rng = np.random.default_rng()

# uniform from 0 to 1

value = rng.random()

# generate 10 Gaussian random number

value = rng.standard_normal(10)

# generate 20 random integers between 0 and 10

value = rng.integers(low=0, high=10, size=20)

# shuffle a sequence in-place

rng.shuffle(sequence)

The object

rng

is a random number generator. You can create multiple such generators, or use the default one. The idea is to allow you to have multiple independent random number generator so drawing random numbers from one generator would not affect another. This would make your code more robust (because you can mitigate the race condition in parallel algorithms) and allows you to fine-tune the pseudo-random number generation algorithm.

TL;DR: How Do I Use the randint Function in Python?

The randint function is part of Python’s random module, and it’s used to generate a random integer within a specified range. Here’s a simple example:


import random number = random.randint(1, 10) print(number) # Output: # (A random number between 1 and 10)

In this example, we’re using Python’s

random.randint()

function to generate a random number between 1 and 10. The

import random

line at the beginning is necessary because randint is part of the random module in Python. The function

random.randint(1, 10)

then generates a random integer within the range of 1 and 10.

If you’re interested in learning more about the randint function, including its more advanced uses and potential issues you might encounter, keep reading for a comprehensive exploration.

Table of Contents

  • Understanding Python’s randint Function
  • Expanding the Range of randint
  • Using randint in Loops
  • Exploring Alternatives to randint
  • Common Issues and Solutions with randint
  • Best Practices with randint
  • Understanding Random Number Generation in Python
  • Real-World Applications of Python’s randint
  • Further Reading: Probability Theory and Statistical Analysis
  • Wrapping Up: Python’s randint Function
What are Random Modules in Python - Explained with Examples  | Python Tutorial
What are Random Modules in Python – Explained with Examples | Python Tutorial

Understanding Random Number Generation in Python

Random number generation is a fundamental concept in programming that has a variety of applications, from game development to data analysis. Python’s

random

module, which includes the

randint()

function, is a powerful tool for generating these random numbers.

The Role of Python’s Random Module

Python’s

random

module provides a suite of functions for generating random numbers. These functions include

randint()

,

random()

,

uniform()

, and many others. Each function generates a random number in a different way or within a different range.


import random random_integer = random.randint(1, 10) random_float = random.random() random_uniform = random.uniform(1.0, 10.0) print(random_integer, random_float, random_uniform) # Output: # (A random integer between 1 and 10, a random float between 0.0 and 1.0, a random float between 1.0 and 10.0)

In this code, we’re using three functions from Python’s

random

module to generate different types of random numbers. Each function provides a unique way to generate random numbers, making the

random

module a versatile tool for random number generation in Python.

The Importance of Randomness in Programming

Randomness plays a crucial role in many areas of programming. For instance, in game development, randomness can be used to create unpredictable gameplay elements. In data analysis, random sampling can help ensure a representative sample of data. By understanding how to generate random numbers in Python, you can harness the power of randomness in your own programming projects.

Python3


import


random


r1


random.randint(


1.23


9.34


print


(r1)

Output :

Traceback (most recent call last):
File “/home/f813370b9ea61dd5d55d7dadc8ed5171.py”, line 6, in
r1=random.randint(1.23, 9.34)
File “/usr/lib/python3.5/random.py”, line 218, in randint
return self.randrange(a, b+1)
File “/usr/lib/python3.5/random.py”, line 182, in randrange
raise ValueError(“non-integer arg 1 for randrange()”)
ValueError: non-integer arg 1 for randrange()

Program to Demonstrate the TypeError

In this example, we can see that if we pass string or character literals as parameters in the randint() function then a TypeError occurs.

Python: generating list of random number using randint function
Python: generating list of random number using randint function

Python3


import


random


r1


random.randint(


10


print


"Random number between 0 and 10 is % s"


(r1))


r2


random.randint(


10


print


"Random number between -10 and -1 is % d"


(r2))


r3


random.randint(


print


"Random number between -5 and 5 is % d"


(r3))

Output

Random number between 0 and 10 is 2
Random number between -10 and -1 is -7
Random number between -5 and 5 is -3

Examples¶

Basic examples:

>>> random() # Random float: 0.0 <= x < 1.0 0.37444887175646646 >>> uniform(2.5, 10.0) # Random float: 2.5 <= x <= 10.0 3.1800146073117523 >>> expovariate(1 / 5) # Interval between arrivals averaging 5 seconds 5.148957571865031 >>> randrange(10) # Integer from 0 to 9 inclusive 7 >>> randrange(0, 101, 2) # Even integer from 0 to 100 inclusive 26 >>> choice([‘win’, ‘lose’, ‘draw’]) # Single random element from a sequence ‘draw’ >>> deck = ‘ace two three four’.split() >>> shuffle(deck) # Shuffle a list >>> deck [‘four’, ‘two’, ‘ace’, ‘three’] >>> sample([10, 20, 30, 40, 50], k=4) # Four samples without replacement [40, 10, 50, 30]

Simulations:

>>> # Six roulette wheel spins (weighted sampling with replacement) >>> choices([‘red’, ‘black’, ‘green’], [18, 18, 2], k=6) [‘red’, ‘green’, ‘black’, ‘black’, ‘red’, ‘black’] >>> # Deal 20 cards without replacement from a deck >>> # of 52 playing cards, and determine the proportion of cards >>> # with a ten-value: ten, jack, queen, or king. >>> deal = sample([‘tens’, ‘low cards’], counts=[16, 36], k=20) >>> deal.count(‘tens’) / 20 0.15 >>> # Estimate the probability of getting 5 or more heads from 7 spins >>> # of a biased coin that settles on heads 60% of the time. >>> sum(binomialvariate(n=7, p=0.6) >= 5 for i in range(10_000)) / 10_000 0.4169 >>> # Probability of the median of 5 samples being in middle two quartiles >>> def trial(): … return 2_500 <= sorted(choices(range(10_000), k=5))[2] < 7_500 … >>> sum(trial() for i in range(10_000)) / 10_000 0.7958

Example of statistical bootstrapping using resampling with replacement to estimate a confidence interval for the mean of a sample:

# https://www.thoughtco.com/example-of-bootstrapping-3126155 from statistics import fmean as mean from random import choices data = [41, 50, 29, 37, 81, 30, 73, 63, 20, 35, 68, 22, 60, 31, 95] means = sorted(mean(choices(data, k=len(data))) for i in range(100)) print(f’The sample mean of {mean(data):.1f} has a 90% confidence ‘ f’interval from {means[5]:.1f} to {means[94]:.1f}’)

Example of a resampling permutation test to determine the statistical significance or p-value of an observed difference between the effects of a drug versus a placebo:

# Example from “Statistics is Easy” by Dennis Shasha and Manda Wilson from statistics import fmean as mean from random import shuffle drug = [54, 73, 53, 70, 73, 68, 52, 65, 65] placebo = [54, 51, 58, 44, 55, 52, 42, 47, 58, 46] observed_diff = mean(drug) – mean(placebo) n = 10_000 count = 0 combined = drug + placebo for i in range(n): shuffle(combined) new_diff = mean(combined[:len(drug)]) – mean(combined[len(drug):]) count += (new_diff >= observed_diff) print(f'{n} label reshufflings produced only {count} instances with a difference’) print(f’at least as extreme as the observed difference of {observed_diff:.1f}.’) print(f’The one-sided p-value of {count / n:.4f} leads us to reject the null’) print(f’hypothesis that there is no difference between the drug and the placebo.’)

Simulation of arrival times and service deliveries for a multiserver queue:

from heapq import heapify, heapreplace from random import expovariate, gauss from statistics import mean, quantiles average_arrival_interval = 5.6 average_service_time = 15.0 stdev_service_time = 3.5 num_servers = 3 waits = [] arrival_time = 0.0 servers = [0.0] * num_servers # time when each server becomes available heapify(servers) for i in range(1_000_000): arrival_time += expovariate(1.0 / average_arrival_interval) next_server_available = servers[0] wait = max(0.0, next_server_available – arrival_time) waits.append(wait) service_duration = max(0.0, gauss(average_service_time, stdev_service_time)) service_completed = arrival_time + wait + service_duration heapreplace(servers, service_completed) print(f’Mean wait: {mean(waits):.1f} Max wait: {max(waits):.1f}’) print(‘Quartiles:’, [round(q, 1) for q in quantiles(waits)])

See also

Statistics for Hackers a video tutorial by Jake Vanderplas on statistical analysis using just a few fundamental concepts including simulation, sampling, shuffling, and cross-validation.

Economics Simulation a simulation of a marketplace by Peter Norvig that shows effective use of many of the tools and distributions provided by this module (gauss, uniform, sample, betavariate, choice, triangular, and randrange).

A Concrete Introduction to Probability (using Python) a tutorial by Peter Norvig covering the basics of probability theory, how to write simulations, and how to perform data analysis using Python.

Keywords searched by users: from random import randint python

Categories: Phổ biến 20 From Random Import Randint Python

The Randint() Method In Python | Digitalocean
The Randint() Method In Python | Digitalocean
The Randint() Method In Python | Digitalocean
The Randint() Method In Python | Digitalocean
Randint Python - A Beginner'S Guide To Randint Python Function
Randint Python – A Beginner’S Guide To Randint Python Function
Python Random.Randint() With Examples - Spark By {Examples}
Python Random.Randint() With Examples – Spark By {Examples}
The Randint() Method In Python | Digitalocean
The Randint() Method In Python | Digitalocean
Random Module-Python
Random Module-Python
How To Generate A Random Number In Python | Python Central
How To Generate A Random Number In Python | Python Central
Question About Random.Randit() - Python - Codecademy Forums
Question About Random.Randit() – Python – Codecademy Forums
Randint Python - A Beginner'S Guide To Randint Python Function
Randint Python – A Beginner’S Guide To Randint Python Function
Random Module-Python
Random Module-Python
Random.Randint Error - Python - Youtube
Random.Randint Error – Python – Youtube
Python Random.Randint() With Examples - Spark By {Examples}
Python Random.Randint() With Examples – Spark By {Examples}
Import Math From Random Import Randint From | Chegg.Com
Import Math From Random Import Randint From | Chegg.Com

See more here: kientrucannam.vn

See more: https://kientrucannam.vn/vn/

Tag:

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *