.getrandbits()
Anonymous contributor
Published Oct 16, 2024
Contribute to Docs
The Python random module generates an integer with a specified number of random bits using the .getrandbits()
method. This method produces an integer value that is uniformly distributed across the range of possible values that can be represented with the specified number of bits.
Syntax
random.getrandbits(k)
k
: The number of bits in the generated integer, which must be a non-negative integer. The result will range from 0 to 2k - 1.
Example
In the example below, .getrandbits()
returns an integer with 256 bits:
import randomrandom_bits = random.getrandbits(256)print(random_bits)
The above code generates the following output:
10657559295629545859200648092091505165182082957984693304497110910582120092295
Note: The output will change every time the code is run because
.getrandbits()
generates a new random integer each time it’s called.
Codebyte Example
Run the following codebyte to understand how the .getrandbits()
method works:
All contributors
- Anonymous contributor
Contribute to Docs
- 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.
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 CoursesWith Professional CertificationBeginner Friendly75 hours - Course
Learn Python 3
Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.With CertificateBeginner Friendly23 hours