Chuyển tới nội dung
Home » Randrange In Python 3 | Notes On Reproducibility¶

Randrange In Python 3 | Notes On Reproducibility¶

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

Next Steps

I want to hear from you. What do you think of this article on

randint()

and

randrange()

? Or maybe I missed one of the usages of those two functions. Either way, let me know by leaving a comment below.

Also, try to solve the following exercise and quiz to have a better understanding of working with random data in Python.

  • Python random data generation Exercise to practice and master the random data generation techniques in Python.
  • Python random data generation Quiz to test your random data generation concepts.

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.

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

All contributors

  1. Anonymous contributorAnonymous contributor3071 total contributions
  2. christian.dinh2476 total contributions
  3. Anonymous contributorAnonymous contributor186 total contributions
  4. BrandonDusch580 total contributions
  1. Anonymous contributor
  2. christian.dinh
  3. Anonymous contributor
  4. BrandonDusch

Looking to contribute?

  • Learn more about how to get involved.
  • Edit this page on GitHub to fix an error or make an improvement.
  • Submit feedback to let us know how we can improve Docs.

Generate a secure random integer

Above all, examples are not cryptographically secure. The cryptographically secure random generator generates random numbers using synchronization methods to ensure that no two processes can obtain the same number simultaneously.

If you are producing random numbers for a security-sensitive application, then you must use this approach.

Use the secrets module if you are using a Python version higher than 3.6.


import secrets # secure random integer # from 0 to 10 secure_num = secrets.randbelow(10) print(secure_num) # Output 5

If you are using Python version less than 3.6, then use the

random.SystemRandom().randint()

or

random.SystemRandom().randrange()

functions.

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

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.

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.

Random number generator in Python
Random number generator in Python

Parameters of randrange Python Function

Start, Stop, and Width are the three input parameters for the random.randrange() function. The two parameters start and width are the only two of these three that can be ignored. These 3 parameters are explained below.

  • A starting or lower limit number in a random range serves as the start parameter. Start takes the default value of 0 if it is not passed in as a parameter.
  • The last or highest number in a random range is referred to as a stop parameter.
  • A range between each number in the random sequence makes up the width parameter. If the width parameter is not provided, this optional parameter takes the default value of 1.

The end parameter is not used when the random integer number is generated by the randrange(start, stop, width) function. The stop parameter is excluded and is not produced by a random number generator.

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()

.

Hàm randrange() trong Python trả về một phần tử được lựa chọn một cách ngẫu nhiên từ dãy (start, stop, step).

Nội dung chính

Python randrange() function | random module
Python randrange() function | random module

Python3


import


random


sum


sum1


count


flag


while


):


r1


random.randrange(


10


r2


random.randrange(


10


sum


sum


r1


sum1


sum1


r2


count


count


print


"Total score of Player 1 after turn %d is : %d "


(count,


sum


))


if


sum


100


):


flag


break


print


"Total score of Player 2 after turn %d is : %d"


(count,sum1))


if


(sum1>


100


):


flag


break


if


(flag


):


print


"\nPlayer 1 wins the game"


else


print


"\nPlayer 2 wins the game"

Output :

Random number from 14.5-100 is :

Runtime Error :

Traceback (most recent call last):
File “/home/5e40f42505a6926d0c75a09bec1279d9.py”, line 9, in
print (random.randrange(14.5,100))
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()

2. Value Error – start >= stop

Output :

Random number from 500-100 is :

Runtime Error :

Traceback (most recent call last):
File “/home/ea327cf3f1dd801a66a185d101c5cb13.py”, line 9, in
print (random.randrange(500,100))
File “/usr/lib/python3.5/random.py”, line 196, in randrange
raise ValueError(“empty range for randrange() (%d,%d, %d)” % (istart, istop, width))
ValueError: empty range for randrange() (500,100, -400)

Practical Application

Generating random numbers has always been an important application and has been used in many casino games, for gambling for many kid games like ludo, etc which use the concept of Dice. A short game, on who reaches 100 first wins have been depicted in the code below. Each player is allowed a dice of 1-10 numbers, i.e at each turn 1-10 can be attained..

Points to remember about randint() and randrange()

  • Use

    randint()

    when you want to generate a random number from an inclusive range.
  • Use

    randrange()

    when you want to generate a random number within a range by specifying the increment. It produces a random number from an exclusive range.

You should be aware of some value constraints of a

randrange()

function.

  • The

    randint(

    ) rand

    randrange()

    works only with integers. You cannot use float numbers.
  • The step must not be 0. If it is set to 0, you will get a

    ValueError: zero step for randrange()
  • The start should not be greater than stop if you are using all positive numbers. If you set start greater than stop, you will get a ValueError: empty range for randrange()

Examples


import random # ValueError: empty range for randrange() print(random.randrange(100, 10, 2))

But, you can also set a start value greater than stop if you are using a negative step value.


import random print(random.randrange(100, 10, -2)) # output 60

14 Randrange function vs randint - Python Tutorial for Beginners (Interactive and Auto-graded)
14 Randrange function vs randint – Python Tutorial for Beginners (Interactive and Auto-graded)

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.

Cú pháp

Cú pháp của randrange() trong Python:

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

Ghi chú: Hàm này không có thể truy cập trực tiếp, vì thế chúng ta cần import math module và sau đó chúng ta cần gọi hàm này bởi sử dụng đối tượng math.

Chi tiết về tham số:

  • start — Điểm bắt đầu của dãy giá trị. Điểm này nên được bao gồm trong dãy.

  • stop — Điểm kết thúc của dãy giá trị. Điểm này nên được loại trừ khỏi dãy.

  • step — Bước để thêm vào trong một số để quyết định một số ngẫu nhiên.

random numbers in python
random numbers in python

Chương trình Python ví dụ

Ví dụ sau minh họa cách sử dụng của randrange() trong Python.

import random # Chon mot so ngau nhien tu 100 <= number < 1000 print “randrange(100, 1000, 2) : “, random.randrange(100, 1000, 2) # Chon mot so ngau nhien khac tu 100 <= number < 1000 print “randrange(100, 1000, 3) : “, random.randrange(100, 1000, 3)

Chạy chương trình Python trên sẽ cho kết quả:

randrange(100, 1000, 2) : 976 randrange(100, 1000, 3) : 520

In this lesson, we will see how to use the

randrange()

and

randint()

functions of a Python random module to generate a random integer number.

Using

randrange()

and

randint()

functions of a random module, we can generate a random integer within a range. In this lesson, you’ll learn the following functions to generate random numbers in Python. We will see each one of them with examples.

Function Description
Returns any random integer from 0 to 9
Returns a random integer from 0 to 19
Returns a random integer from 2 to 19.
Returns any random integer from 100 to 999 with step 3. For example, any number from 100, 103, 106 … 994, 997.
Returns a random negative integer between -50 to -6.
Returns a list of random numbers
Returns a secure random number

Example

The following example shows the usage of randrange() method.

#!/usr/bin/python import random # Select an even number in 100 <= number < 1000 print “randrange(100, 1000, 2) : “, random.randrange(100, 1000, 2) # Select another number in 100 <= number < 1000 print “randrange(100, 1000, 3) : “, random.randrange(100, 1000, 3)

When we run above program, it produces following result −

randrange(100, 1000, 2) : 976 randrange(100, 1000, 3) : 520

python_numbers.htm

Advertisements

randrange() Python Function

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

Python3


import


random


print


"Random number from 500-100 is : "


,end


"")


print


(random.randrange(


500


100


))

Output:

Random number from 0-100 is : 26
Random number from 50-100 is : 58
Random number from 50-100 skip 5 is : 90

Exceptions

1. Value Error – Floating point value

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.

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

How to use random.randint()

Syntax:


random.randint(start, stop)

This function returns a random integer between a given start and stop integer.

Parameters:

It takes two parameters. Both are mandatory.


  • start

    : It is the start position of a range. The default value is 0 if not specified.

  • stop

    : It is the end position of a range.

Return value:

It will generate any random integer number from the inclusive range. The

randint(start, stop)

consider both the start and stop numbers while generating random integers

How to use Python

randint()

and

randrange()

to get random integers

  1. Import random module

    Use Python’s random module to work with random data generation.

    import it using a

    import random

    statement.

  2. Use randint() Generate random integer

    Use a


    random.randint()

    function to get a random integer number from the inclusive range. For example,

    random.randint(0, 10)

    will return a random number from [0, 1, 2, 3, 4, 5, 6, 7, 8 ,9, 10].

  3. Use the randrnage() function to generate a random integer within a range

    Use a


    random.randrange()

    function to get a random integer number from the given exclusive range by specifying the increment. For example,

    random.randrange(0, 10, 2)

    will return any random number between 0 and 20 (like 0, 2, 4, 6, 8).

random.randint() example of generating random number


import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84

Note: You cannot use float numbers in

randint()

. It will raise a ValueError (

non-integer stop for randrange()

) if you use non-integer numbers. Please, read how to generate a random float number within a range.

Uses of randrange Python Function

  • It has always been essential to generate random numbers in applications since they have several real-time applications in daily life. An OTP (one-time password) is a random number that is generated and sent to a customer to facilitate a secure transaction.
  • When playing the game of Ludo, a random dice number is generated as an additional example of generating a randomly selected number.
  • In casino games, this random number generator is frequently used.
  • In online bike and car racing games, we have given a random number position, this random number generator is used.
C++ Random Number Generator AKA STOP USING Rand()
C++ Random Number Generator AKA STOP USING Rand()

Random negative integer

Let’s see how to generate a random negative integer between -60 to -6.


import random singed_int = random.randrange(-60, -6) print(singed_int) # Output -16

Generate random positive or negative integer


import random for i in range(5): print(random.randint(-10, 10), end=' ') # Output 10 -1 5 -10 -7

Randomly generate 1 or -1


import random num = random.choice([-1, 1]) print(num)

Note: we used random.choice() to choose a single number from the list of numbers. Here our list is

[-1, 1]

.

Working of randrange Python Function

Within the start and stop points that are passed to the randrange() function, the random.randrange() function returns a random number. Start, Stop, and Width are the three parameters that the random.randrange() function accepts as input. The two parameters start and width are optional out of these three.

The end parameter is not used when the random integer number is generated by the randrange(start, stop, width) function. The stop parameter is unique and is not produced by a random number generator.

Consider the function random.randrange(2, 20, 2), which will produce any random integer value between 3 and 30 such as 2, 4, 6, 8,… . But when producing a random number, this algorithm never takes 20 into account.

How to Build all Classifiers in Python - Random Forest, Decision Tree, Naive Bayes, SVM, LR, GB...
How to Build all Classifiers in Python – Random Forest, Decision Tree, Naive Bayes, SVM, LR, GB…

Python3


import


random


sum


sum1


count


flag


while


):


r1


random.randrange(


10


r2


random.randrange(


10


sum


sum


r1


sum1


sum1


r2


count


count


print


"Total score of Player 1 after turn %d is : %d "


(count,


sum


))


if


sum


100


):


flag


break


print


"Total score of Player 2 after turn %d is : %d"


(count,sum1))


if


(sum1>


100


):


flag


break


if


(flag


):


print


"\nPlayer 1 wins the game"


else


print


"\nPlayer 2 wins the game"

Output

Total score of Player 1 after turn 1 is : 8
Total score of Player 2 after turn 1 is : 4
Total score of Player 1 after turn 2 is : 13
Total score of Player 2 after turn 2 is : 8
Total score of Player 1 after turn 3 is : 22
Total score of Player 2 after turn 3 is : 16
Total score of Player 1 after turn 4 is : 28
Total score of Player 2 after turn 4 is : 22
Total score of Player 1 after turn 5 is : 33
Total score of Player 2 after turn 5 is : 27
Total score of Player 1 after turn 6 is : 35
Total score of Player 2 after turn 6 is : 33
Total score of Player 1 after turn 7 is : 36
Total score of Player 2 after turn 7 is : 42
Total score of Player 1 after turn 8 is : 38
Total score of Player 2 after turn 8 is : 50
Total score of Player 1 after turn 9 is : 45
Total score of Player 2 after turn 9 is : 55
Total score of Player 1 after turn 10 is : 48
Total score of Player 2 after turn 10 is : 61
Total score of Player 1 after turn 11 is : 54
Total score of Player 2 after turn 11 is : 64
Total score of Player 1 after turn 12 is : 57
Total score of Player 2 after turn 12 is : 70
Total score of Player 1 after turn 13 is : 66
Total score of Player 2 after turn 13 is : 73
Total score of Player 1 after turn 14 is : 72
Total score of Player 2 after turn 14 is : 75
Total score of Player 1 after turn 15 is : 79
Total score of Player 2 after turn 15 is : 76
Total score of Player 1 after turn 16 is : 81
Total score of Player 2 after turn 16 is : 77
Total score of Player 1 after turn 17 is : 89
Total score of Player 2 after turn 17 is : 81
Total score of Player 1 after turn 18 is : 95
Total score of Player 2 after turn 18 is : 90
Total score of Player 1 after turn 19 is : 97
Total score of Player 2 after turn 19 is : 99
Total score of Player 1 after turn 20 is : 102
Player 1 wins the game

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 :
10 Sep, 2020

Like Article

Save Article

Share your thoughts in the comments

Please Login to comment…

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.

Return Value of randrange Python Function

The randrange() function in Python returns a random integer from a range of values. The range is determined by the arguments passed to the function, with one argument generating a random integer between 0 and the stop value, two arguments generating a random integer between the start and stop values, and three arguments generating a random integer that is a multiple of the step value within the specified range. This function is useful for generating random integers in Python for various applications.

How to Make 2500 HTTP Requests in 2 Seconds with Async & Await
How to Make 2500 HTTP Requests in 2 Seconds with Async & Await

random.randrange() to generate random integers within a range

Now let’s see how to use the

random.randrange()

function to get a random integer number from the given exclusive range by specifying the increment.

Syntax


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

This function returns a random integer from a

range(start, stop, step)

. For example,

random.randrange(0, 10, 2)

will generate any random numbers from [0, 2, 4, 6, 8].

Parameters

It takes three parameters. Out of three, two parameters are optional. i.e.,

start

and

step

are optional.


  • start

    : it is the star number in a range. i.e., lower limit. The default value is 0 if not specified.

  • stop

    : It is the end/last number in a range. It is the upper limit.

  • step

    : Specify the increment value in range. The generated random number is divisible by step. The default value is 1 if not specified.

random.randrange() examples

In the following example, we are trying to print a random int in a given range. This example demonstrates all the variants of

random.randrange()

function.


import random # random integer from 0 to 9 num1 = random.randint(0, 9) print(num1) # output 5 # Random integer from 10 to 100 num2 = random.randint(10, 100) print(num2) # Output 84

Note:

  • The

    randrange()

    doesn’t consider the stop number while generating a random integer. It is an exclusive random range. For example,

    randrange(2, 20, 2)

    will return any random number between 2 to 20, such as 2, 4, 6, …18. It will never select 20.
  • Same as

    randint()

    , you cannot use float value in

    randrange()

    too. It will raise a

    ValueError

    (non-integer arg 1 for randrange()) if you use non-integers.

Random number of a specific length

Let’s see how to generate a random number of length n. For example, any random number of length four, such as 7523, 3674. We can accomplish this using both

randint()


randrange()

.


import random # random number of length 4 num1 = random.randint(1000, 9999) # random number of length 4 with step 2 num2 = random.randrange(1000, 10000, 2) print(num1, num2) # Output 3457 5116

Note: As you can see, we set a

start = 1000

and a

stop = 10000

because we want to generate the random number of length 4 (from 1000 to 9999).

Random integer number multiple of n

For example, let’s generate a random number between x and y multiple of 3 like 3, 6, 39, 66.


import random num = random.randrange(3, 300, 3) print(num) # output 144

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.

Implementing Random Forest In Python|How to Implement Random Forest In Python|Random Forest ML
Implementing Random Forest In Python|How to Implement Random Forest In Python|Random Forest ML

Exceptions of randrange Python Function

ValueError is raised if stop <= start and the integer is not integral. Let’s understand it with an example given below.

Output

Now as given in the above example, the value of start>end so it is raising an ValueError. So it means we can’t provide the start>end in randrange Python function otherwise it will raise ValueError.

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.

3 Mini Python Projects - For Beginners
3 Mini Python Projects – For Beginners

Table of contents

  • How to use random.randint()
  • random.randrange() to generate random integers within a range
  • Random negative integer
  • Generate a list of random integer numbers
  • Generate a secure random integer
  • Create a multidimensional array of random integers
  • Points to remember about randint() and randrange()
  • Next Steps

Overview

The randrange() function is a built-in Python function used to generate random integers between a given start and stop value. It is a part of the random module and can be used for various purposes like generating random passwords, selecting a random element from a list, or shuffling a deck of cards. The function takes at least one argument for the stop value, and can also take an optional argument for the start value and a step value. The function returns a random integer between the given range, with the start value being inclusive and the stop value being exclusive.

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

Ví dụ hàm randrange() Python

Ví dụ sau minh họa cách sử dụng của randrange() trong Python.

import random # Chon mot so ngau nhien tu 100 <= number < 1000, number chia het cho 1 print (“randrange(100, 1000, 1) : “, random.randrange(100, 1000, 1)) # Chon mot so ngau nhien khac tu 100 <= number < 1000, number chia het cho 5 print (“randrange(100, 1000, 5) : “, random.randrange(100, 1000, 5))

Chạy chương trình Python trên sẽ cho kết quả:

randrange(100, 1000, 1) : 515 randrange(100, 1000, 5) : 790

Python random randrange()

The Python random module allows generating random numbers. The generated numbers are a sequence of pseudo-random numbers, which are based on the used function. There are different types of functions used in a random module to generate random numbers, such as random.random(), random.randint(), random.choice(), random.randrange(start, stop, width), and many more.

Here, we will discuss the randrange() function of the random module. The randrange() function is used to generate a random number between the specified range in its parameter. It accepts three parameters: starting number, stop number, and width, which is used to skip a number in the range.

Syntax of random.randrange()

The random.randrange() function returns a random integer number within the given range, i.e., start and stop. The random.randrange() function takes three parameters as an input start, stop, and width. Out of these three parameters, the two parameters start and width are optional.

The randrange(start, stop, width) function does not include the end parameter while generating the random integer number. The stop parameter is exclusive, and it not gets generated in a random number.

Look at this random.randrange(3, 30, 3) function that will generate any random integer value between 3 to 30 like 3, 6, 9, 12, …27. But this function never includes 30 while generating a random number.

Generating a random in an application always been important, and it has several real-time uses in day-to-day life. For example, generating and sending a random number to a customer as an OTP (one-time-password) for making a safe transaction. Another example of generating a random number is used while playing the ludo game to generate a random dice number.

Examples 1: random.randrange() generate a random integers number within the given range

Let’s see an example where we are generating a random integer number within a given range. This example shows all the different forms of random.randrange() function.

Output:

Example 2: Generate a random integer number range (multiple) of n

Let’s generate the random integer number between 5 to 100, which is a range of 5 such as 5, 10, 25, …, 90, 95.

Output:

Example 3: Generate the random integer number of a specific length

You can also generate a random integer number of a specific length. If you want to generate a random number of length 3, input the start and stop parameter in randrange() function as least number of 3 digit length (100) and least number of 4 digit length (1000) because it generates a random number of 3 digit form 100 to 999 where 4 digits (1000) is excluded.

Example: Generate a random number of 3 digit using random.randrange()

Output:

First random number of length 3 is: 813 Second random number of length 3 is: 770

Example 4: Generate a random negative integer number:

Let’s see an example that generates a random negative integer number between -50 to -10.

Output:

Random negative integer number between -50 to -10 Random negative integer number between -50 to -10 is: -43

Example 5: Generate random positive or negative integer number

Output:

-5 0

Note that the parameter start and stop, which is passed in random.randrange() function must be in increasing order, such as random.randrange(5, 10) or random.randrange(-20, -10). The start parameter always be smaller than the stop parameter; otherwise, this function generates an error as “Traceback (most recent call last) and raise ValueError empty range for randrange()”.

For example:

Look at this example in which we are violating the rule by passing the start parameter greater than the stop parameter in random.randrange() function, which generates an error message as:

Output:

Some of the other functions of Python’s random module that are used to generate numbers randomly are:

random.choice()

Python random module has a choice() function used to choose a random element from a list or other sequence. A random.choice() function is used to returns a random element from the list of values.

Syntax of ramdom.choice()

or

Here the parameter sequence can be string, list, tuple, and random.choice() only a single random element.

In the random.choices() function k is the number of elements to be returned. Suppose we don’t mention the value for k parameter the random.choices() returns a single item from the sequence or list.

Example 1:

In this example, we are providing on sequence (list) as a parameter and returning a single random element.

Output:

random item from list is: 10

Example 2:

The random.choices() function is mostly used for returning random elements with various possibilities. This function also takes weight (k) the number of random choices. For example, we want to print 3 random movies name from list of 5 movies.

Output:

random movies from list are: [‘Avengers’, ‘Black Panther’, ‘Titanic’]

random.randint()

Python random.randint() function is used to generate a random integer number within the specified range.

Syntax:

The random.randint() function takes two parameters start, which is a starting range, and stop, which is an end range. Both parameters (start, stop) are included while generating a random number.

Example of random.randint() generating a list of random integer

This example will create a list of multiple random integers using the randint() function. Generating a list of 5 random integers between 1 and 100, both values are inclusive.

Output:

Printing list of 5 generated random numbers [65, 82, 3, 39, 40]

However, there may be a possibility that the random.randint() function returns a duplicate number in the output result. To avoid the duplicate random integer number in a result, use random.sample() function.

random.sample()

In the above example, there may be a possibility that random.randint() generates the duplicate random number from the list. If you want to generate unique random numbers from a list, use random.sample() function.

The random.sample() function generates unique elements from a set, list, and other sequences. Python’s random.sample() function allows random sampling of more than one element within a range from the list without duplicating.

Example of a random.sample() to generate random elements from a list without duplicates:

In this example, we will generate 10 random integers from the range 0 to 100.

Output:

[15, 17, 16, 66, 34, 85, 71, 82, 97, 48]

If you want to generate a list of random numbers and each of them must be multiple of ‘n’, then use the step parameter of range() function.

For example, generating 10 random integers which are multiple of 5 from the range 0 to 100 using random.sample(range(0, 100, 5), 10).

Output:

[75, 40, 20, 55, 15, 10, 5, 90, 95, 70]

List sort()

The Python sort() function is used to sort the random integer numbers of the list in ascending order (by default). We can also sort the list value in descending order by specifying its order reverse = True. The default value of reverse is False.

Example 1: sort() sorting list elements in ascending order

In this example, we will generate a random list of 5 numbers in a range of 50 to 100 with the width of 5 and sort them using sort() function.

Output:

Before sorting random integers list [90, 80, 60, 55, 85] After sorting random integers list [55, 60, 80, 85, 90]

Example 2: sort() sorting list elements in descending order

In this example, we will sort the list elements in descending order using randomList.sort(reverse=True).

Output:

Before sorting random integers list [70, 50, 80, 90, 85] After sorting random integers list [90, 85, 80, 70, 50]

Next TopicPermutation and Combination in Python

.randrange()

Anonymous contributor

Anonymous contributor3071 total contributions

Anonymous contributor

Published May 10, 2021Updated Mar 9, 2022

Contribute to Docs

The

.randrange()

method selects a random number from a defined range of

int

values.

Parameter Values

Parameter Description
start Optional. An integer specifying at which position to start.

Default 0

stop Required. An integer specifying at which position to end.
step Optional. An integer specifying the incrementation.

Default 1

Generating a random number has always been an important application and having many uses in daily life. Python offers a function that can generate random numbers from a specified range and also allowing rooms for steps to be included, called randrange() in random module. More to this function is discussed in this article.

Syntax :
random.randrange(start(opt),stop,step(opt))
Parameters :
start(opt) : Number consideration for generation starts from this,
default value is 0. This parameter is optional.
stop : Numbers less than this are generated. This parameter is mandatory.
step(opt) : Step point of range, this won’t be included. This is optional.
Default value is 1.
Return Value :
This function generated the numbers in the sequence start-stop skipping step.
Exceptions :
Raises ValueError if stop <= start and number is non- integral.

How to Use \
How to Use \”break\” and \”continue\” in Python \”while\” Loops

Learn Python on Codecademy

Career path

Computer Science

Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!

Includes 6 Courses

With Professional Certification

Beginner Friendly

80 hours

Career path

Data Scientist: Machine Learning Specialist

Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.

Includes 27 Courses

With Professional Certification

Beginner Friendly

90 hours

  • Python Basics
  • Python – Home
  • Python – Overview
  • Python – History
  • Python – Features
  • Python vs C++
  • Python – Hello World Program
  • Python – Application Areas
  • Python – Interpreter
  • Python – Environment Setup
  • Python – Virtual Environment
  • Python – Basic Syntax
  • Python – Variables
  • Python – Data Types
  • Python – Type Casting
  • Python – Unicode System
  • Python – Literals
  • Python – Operators
  • Python – Arithmetic Operators
  • Python – Comparison Operators
  • Python – Assignment Operators
  • Python – Logical Operators
  • Python – Bitwise Operators
  • Python – Membership Operators
  • Python – Identity Operators
  • Python – Operator Precedence
  • Python – Comments
  • Python – User Input
  • Python – Numbers
  • Python – Booleans
  • Python Control Statements
  • Python – Control Flow
  • Python – Decision Making
  • Python – If Statement
  • Python – If else
  • Python – Nested If
  • Python – Match-Case Statement
  • Python – Loops
  • Python – for Loops
  • Python – for-else Loops
  • Python – While Loops
  • Python – break Statement
  • Python – continue Statement
  • Python – pass Statement
  • Python – Nested Loops
  • Python Functions & Modules
  • Python – Functions
  • Python – Default Arguments
  • Python – Keyword Arguments
  • Python – Keyword-Only Arguments
  • Python – Positional Arguments
  • Python – Positional-Only Arguments
  • Python – Arbitrary Arguments
  • Python – Variables Scope
  • Python – Function Annotations
  • Python – Modules
  • Python – Built in Functions
  • Python Strings
  • Python – Strings
  • Python – Slicing Strings
  • Python – Modify Strings
  • Python – String Concatenation
  • Python – String Formatting
  • Python – Escape Characters
  • Python – String Methods
  • Python – String Exercises
  • Python Lists
  • Python – Lists
  • Python – Access List Items
  • Python – Change List Items
  • Python – Add List Items
  • Python – Remove List Items
  • Python – Loop Lists
  • Python – List Comprehension
  • Python – Sort Lists
  • Python – Copy Lists
  • Python – Join Lists
  • Python – List Methods
  • Python – List Exercises
  • Python Tuples
  • Python – Tuples
  • Python – Access Tuple Items
  • Python – Update Tuples
  • Python – Unpack Tuples
  • Python – Loop Tuples
  • Python – Join Tuples
  • Python – Tuple Methods
  • Python – Tuple Exercises
  • Python Sets
  • Python – Sets
  • Python – Access Set Items
  • Python – Add Set Items
  • Python – Remove Set Items
  • Python – Loop Sets
  • Python – Join Sets
  • Python – Copy Sets
  • Python – Set Operators
  • Python – Set Methods
  • Python – Set Exercises
  • Python Dictionaries
  • Python – Dictionaries
  • Python – Access Dictionary Items
  • Python – Change Dictionary Items
  • Python – Add Dictionary Items
  • Python – Remove Dictionary Items
  • Python – Dictionary View Objects
  • Python – Loop Dictionaries
  • Python – Copy Dictionaries
  • Python – Nested Dictionaries
  • Python – Dictionary Methods
  • Python – Dictionary Exercises
  • Python Arrays
  • Python – Arrays
  • Python – Access Array Items
  • Python – Add Array Items
  • Python – Remove Array Items
  • Python – Loop Arrays
  • Python – Copy Arrays
  • Python – Reverse Arrays
  • Python – Sort Arrays
  • Python – Join Arrays
  • Python – Array Methods
  • Python – Array Exercises
  • Python File Handling
  • Python – File Handling
  • Python – Write to File
  • Python – Read Files
  • Python – Renaming and Deleting Files
  • Python – Directories
  • Python – File Methods
  • Python – OS File/Directory Methods
  • Object Oriented Programming
  • Python – OOPs Concepts
  • Python – Object & Classes
  • Python – Class Attributes
  • Python – Class Methods
  • Python – Static Methods
  • Python – Constructors
  • Python – Access Modifiers
  • Python – Inheritance
  • Python – Polymorphism
  • Python – Method Overriding
  • Python – Method Overloading
  • Python – Dynamic Binding
  • Python – Dynamic Typing
  • Python – Abstraction
  • Python – Encapsulation
  • Python – Interfaces
  • Python – Packages
  • Python – Inner Classes
  • Python – Anonymous Class and Objects
  • Python – Singleton Class
  • Python – Wrapper Classes
  • Python – Enums
  • Python – Reflection
  • Python Errors & Exceptions
  • Python – Syntax Errors
  • Python – Exceptions
  • Python – try-except Block
  • Python – try-finally Block
  • Python – Raising Exceptions
  • Python – Exception Chaining
  • Python – Nested try Block
  • Python – User-defined Exception
  • Python – Logging
  • Python – Assertions
  • Python – Built-in Exceptions
  • Python Multithreading
  • Python – Multithreading
  • Python – Thread Life Cycle
  • Python – Creating a Thread
  • Python – Starting a Thread
  • Python – Joining Threads
  • Python – Naming Thread
  • Python – Thread Scheduling
  • Python – Thread Pools
  • Python – Main Thread
  • Python – Thread Priority
  • Python – Daemon Threads
  • Python – Synchronizing Threads
  • Python Synchronization
  • Python – Inter-thread Communication
  • Python – Thread Deadlock
  • Python – Interrupting a Thread
  • Python Networking
  • Python – Networking
  • Python – Socket Programming
  • Python – URL Processing
  • Python – Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python – Date & Time
  • Python – Maths
  • Python – Iterators
  • Python – Generators
  • Python – Closures
  • Python – Decorators
  • Python – Recursion
  • Python – Reg Expressions
  • Python – PIP
  • Python – Database Access
  • Python – Weak References
  • Python – Serialization
  • Python – Templating
  • Python – Output Formatting
  • Python – Performance Measurement
  • Python – Data Compression
  • Python – CGI Programming
  • Python – XML Processing
  • Python – GUI Programming
  • Python – Command-Line Arguments
  • Python – Docstrings
  • Python – JSON
  • Python – Sending Email
  • Python – Further Extensions
  • Python – Tools/Utilities
  • Python – GUIs
  • Python Useful Resources
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
  • Python – Programming Examples
  • Python – Quick Guide
  • Python – Useful Resources
  • Python – Discussion

Python Number randrange() Method

Create a multidimensional array of random integers

Python’s NumPy module has a

numpy.random

package to generate random data. To create a random multidimensional array of integers within a given range, we can use the following NumPy methods:


  • randint()

  • random_integers()

  • np.randint(low[, high, size, dtype])

    to get random integers array from low (inclusive) to high (exclusive).

  • np.random_integers(low[, high, size])

    to get random integer’s array between low and high, inclusive.

Now, Let see the example.

Generate a 4 x 4 array of ints between 10 and 50, exclusive:


import numpy # 4 x 4 array newArray = numpy.random.randint(10, 50, size=(4, 4)) print(newArray)

Output:

[[10 48 30 24] [13 46 30 11] [12 28 49 26] [30 18 49 35]]

Generate a 5 x 3 array of random integers between 60 and 100, inclusive.


import numpy # 3 x 5 array of ints newArray = numpy.random.random_integers(60, 100, size=(3, 5)) print(newArray)

Output:

[[63 76 95 93 75] [71 84 63 99 93] [65 64 66 69 92]]

Generating ACTUALLY Random Numbers in Python
Generating ACTUALLY 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.

Examples of randrange Python Function

Example 1: Generating a Rndom Integer Number Within the Given Range

Let’s look at an instance where we generate a random integer number from a range. This example demonstrates every variation of the random.randrange() function.

Output

As we have generated 3 random number with all three different cases. For generating num1 we just have passed 50, which will be taken by the randrange function as end limit. The start paramater will be 0(by default) here. So the num1 will be between 0 and 50. And for generating num2 we have passed 20 as starting parameter and 50 as an ending parameter. These 2 are when passed to this randrange function it will return num2 which will be between 20 and 50. At last for generating the random number between 30 and 60 but also it should be the multiple of 4, we have passed 30 in place of parameterm 60 in place of ending parameter and 4 in place of width paramter.

Example 2: Generate a Random Integer Number within the Range (multiple) of n

Let’s create a random number in the range of 10 to 90, such as 10, 20, 30,…, 80.

Output

In the example given above we want a random number between 10 and 90 but it should be a multiple of 10, so we will pass 10 as a width parameter and as a result randrange function will generate a randome number between 10 and 90 which is a multiple of 10.

Example 3: Generate a Random Integer Number with a Specific Length.

Additionally, you can produce random integers with a predetermined length. The randrange python function generates a random number of 3 digits from 100 to 999 where 4 digits (1000) is excluded, thus if you want to get a random number of length 3, enter the start and stop parameters as lowest number of 3 digit length (100) and least number of 4 digit length (1000).

Output

As we want a 3 digit number so we have pass starting limit which is of 3 digit itself and the ending limit should be the first 4 digit number, then only the random number which will be produced can be of 3 digit. So in the above example we have passed 100 as an starting limit(first 3 digit number) and 1000(first 4 digit number) as an end limit.

Example 4: Generate a Random Negative Integer Number.

A random negative integer value between -40 and -20 will be generated in the following example.

Output

In the example given above, both starting and ending limit of the range are passed negative to the randrange function. So it will return a any randome negative number that lies between -40 and -20.

Example 5: Generate Random Positive or Negative Integer Number

Output

As we can observe that range is given between -6 and 10, so when we passed these -6,10 inside the randrange function it have returned -3 in first time and on second time it have returned 6.

Massively Speed Up Requests with HTTPX in Python
Massively Speed Up Requests with HTTPX in Python

Cú pháp

Cú pháp của randrange() trong Python:

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

Ghi chú: Hàm này không có thể truy cập trực tiếp, vì thế chúng ta cần import random module và sau đó chúng ta cần gọi hàm này bởi sử dụng đối tượng random.

Chi tiết về tham số:

  • start : Điểm bắt đầu của dãy giá trị. Điểm này nên được bao gồm trong dãy.

  • stop : Điểm kết thúc của dãy giá trị. Điểm này nên được loại trừ khỏi dãy.

  • step : Bước để thêm vào trong một số để quyết định một số ngẫu nhiên.

Generate a list of random integer numbers

In this section, we will see how to generate multiple random numbers. Sometimes we need a sample list to perform testing. In this case, instead of creating it manually, we can create a list with random integers using a

randint()

or

randrange()

. In this example, we will see how to create a list of 10 random integers.


import random random_list = [] # Set a length of the list to 10 for i in range(0, 10): # any random numbers from 0 to 1000 random_list.append(random.randint(0, 1000)) print(random_list) # Output [994, 287, 65, 994, 936, 462, 839, 160, 689, 624]

Create a list of random numbers without duplicates

Note: In the above example, there is a chance of occurring a duplicate number in a list.

If you want to make sure each number in the list is unique, use the random.sample() method to generate a list of unique random numbers.

  • The

    sample()

    returns a sampled list of selected random numbers within a range of values.
  • It never repeats the element so that we can get a list of random numbers without duplicates


import random # Generate 10 unique random numbers within a range num_list = random.sample(range(0, 1000), 10) print(num_list) # Output [499, 580, 735, 784, 574, 511, 704, 637, 472, 211]

Note: You can also use the step parameter of the range() function to specify the increment. For example, you want a list of 10 random numbers, but each integer in a list must be divisible by 5, then use

random.sample(range(0, 1000, 5), 10)

Sort random numbers list

Use the

sort()

function to sort a list of random integers in ascending order


import random sample_list = random.sample(range(50, 500, 5), 5) # Before sorting print(sample_list) # Output [305, 240, 260, 235, 445] sample_list.sort() # After sorting print(sample_list) # Output [235, 240, 260, 305, 445]

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

Conclusion

  • Any random integer number can be generated using randrange Python function.
  • Start and width parameters can be ignored by calling function.
  • Random generation of number is widely used in casino games.
  • Stop parameter value is excluded while generation of random number.

Phương thức Number randrange() trong Python

Keywords searched by users: randrange in python 3

The Randint() Method In Python | Digitalocean
The Randint() Method In Python | Digitalocean
Random Module-Python
Random Module-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
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
Python Random Randrange() Function - Spark By {Examples}
Python Random Randrange() Function – Spark By {Examples}
Random — Generate Pseudo-Random Numbers — Python 3.12.2 Documentation
Random — Generate Pseudo-Random Numbers — Python 3.12.2 Documentation
Numpy Tutorial For Beginners - How To Use Numpy Random.Randint() - Youtube
Numpy Tutorial For Beginners – How To Use Numpy Random.Randint() – Youtube
Randint Python - A Beginner'S Guide To Randint Python Function
Randint Python – A Beginner’S Guide To Randint Python Function
Python Programming Tutorial # 219 | The Random, Randint , And Randrange  Functions In Python - Youtube
Python Programming Tutorial # 219 | The Random, Randint , And Randrange Functions In Python – Youtube
Solved Using Python In Eclipses. Trying To Solve... My | Chegg.Com
Solved Using Python In Eclipses. Trying To Solve… My | Chegg.Com
How To Write A Python Program For Generating A List Of Random Numbers That  Vary From 100 To 999 Without Repetition - Quora
How To Write A Python Program For Generating A List Of Random Numbers That Vary From 100 To 999 Without Repetition – Quora

See more here: kientrucannam.vn

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 *