dir() is an essential tool when exploring a module’s attributes. It returns an alphabetically sorted list of all the functions, constants, and other attributes available in a module. For example, if you want to see what the math module offers, you can use the following code:
random module provides a variety of functions to generate pseudo-random numbers. Although these numbers seem random, they are produced by deterministic algorithms, and their outcomes can be reproduced if you set a specific seed.
Generating Random Floats
To obtain a random floating-point number in the range [0.0, 1.0), you can use therandom() function:
seed() function:
For consistent results across executions, always set a fixed seed when generating random numbers.
Generating Random Integers
If you need random integers, you can choose between therandint and randrange functions:
- The
randint(a, b)function returns an integer N such that a ≤ N ≤ b. For example, to generate a random integer between 0 and 9:
- The
randrange()function follows Python’s range semantics. When given a single parameter, it returns a random integer from 0 up to (but not including) that number:
randrange(start, stop, step) to define a specific step interval. For example, generating a number from the values 0, 3, 6, or 9 within the range 0 to 10 is done as follows:
Random Selection from a List
In addition to generating random numbers, therandom module includes functions to select items from collections:
- Use
choice()to pick a single random element from a list. - Use
sample(population, k)to retrieve a list of k unique elements from the given list.
math and random modules in Python. Start experimenting with these functions to better understand the power of Python’s standard library and enhance your coding projects. Happy coding!