What is Python help() Function?

The Python help() is a built-in function that provides on-demand documentation and information about Python objects. It serves as a built-in interactive help system, allowing you to access information about Python modules, classes, functions, methods, and other objects. Python help() displays useful documentation, including docstrings and other details, that can aid in understanding how to use Python constructs efficiently.

To utilize Python help() function in real-world scenarios, it is crucial to understand its syntax and parameters. Familiarizing yourself with these aspects is vital as they play a significant role in executing the examples. By gaining a solid understanding of the function’s syntax and parameters, you can maximize its potential in various situations.

Python help() Syntax and Parameters

The syntax of the Python help() function is quite straightforward, making it easy to use in your code. To access it, you simply need to call the help() function with an arguments. Here’s the basic syntax:

help(object)

Here, object is the Python object you want to get information about. It can be any valid Python object. But the help() function also has a few optional parameters that allow you to control the output and the way information is displayed. Let’s delve deeper into these parameters and examine them thoroughly:

I. Object

As previously discussed, this is the specific object for which you are seeking assistance. This object could encompass a wide variety of Python entities, ranging from data structures to user-defined classes.

II. Globals

Globals parameter is an optional dictionary that acts as a global symbol dictionary and can be utilized as the overarching namespace when you request help for a particular object.

III. Locals

The locals parameter is an optional dictionary that works like the globals parameter. It serves as a local symbol dictionary and functions as the main namespace when seeking help for a specific object.

As previously mentioned, Python help() plays a vital role in retrieving and presenting information about various Python objects that you encounter during coding. Now, let’s investigate its functionalities through different scenarios to enhance your understanding. By delving into these examples, you’ll develop a more profound comprehension of Python help() function and its efficient application in the Python programming codes.

I. Creation of the help() Object

The creation of a help() object allows you to access the built-in help system of Python, which provides detailed information. This object serves as a gateway to the extensive documentation available within the Python environment. Consider the following example:

Example Code
help_obj = help() print(help_obj)

In this example, we are creating a help() object and then printing its contents. When we call help() without passing any arguments, it launches the Python help system in an interactive mode. The help() function displays an introductory message that provides information about the Python help utility and how to use it. The help_obj variable captures this introductory message.

After running the code, when we print the value of the help_obj variable, it will display the introductory message of the Python help system. This message typically includes details about how to use the help system, such as typing help() for interactive help and help(object) to get help about a specific object.

Output
Welcome to Python 3.10’s help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the internet at https://docs.python.org/3.10/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules. To quit this help utility and
return to the interpreter, just type “quit”.

To get a list of available modules, keywords, symbols, or topics, type
“modules”, “keywords”, “symbols”, or “topics”. Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as “spam”, type “modules spam”.

help>

While utilizing it, remember that the precise message might differ based on the version of Python you’re using.

II. Python help() Function Docstring

A docstring serves as a string literal utilized as the initial statement in the definition of a module, function, class, or method. It provides useful information about the object’s purpose, usage, and parameters. When you call help() on an object, Python looks for the docstring associated with that object and displays it as part of the interactive help information. For example:

Example Code
def greet(name): """This function greets the person with the given name.""" print(f"Hello, {name}!") help(greet)

Here, we’ve defined a Python function called greet() that takes a parameter called name. Right after the function definition, we’ve added a docstring enclosed in triple quotes. This docstring serves as a brief description of what the function does – in this case, it’s a greeting function that takes a person’s name and prints a greeting message.

Now, using Python help() function, we’re accessing the documentation of the greet() function. When we run the code, the help() function displays the docstring we provided for the greet() function.

Output
Help on function greet in module __main__:

greet(name)
This function greets the person with the given name.

This helps anyone reading the code to understand the purpose of the function and how to use it correctly.

Different Ways to Use help()

As illustrated in the preceding examples, utilizing Python help() is quite simple and provides convenient access to Python documentation. Now, let’s delve deeper and discover various methods of employing the help() function across different scenarios. This exploration will broaden your understanding of how to leverage help() in various contexts.

I. Getting Help for Built-in Functions

Getting Help for Built-in Functions allows you to access detailed documentation about Python’s built-in functions using the help() function. This functionality enables you to access insights into how these functions work. By utilizing this feature, you can gain a better understanding of the built-in functions and integrate them into your code. For instance:

Example Code
print("Python len function: \n") print(help(len)) print("\n\nPython len function: \n") print(help(abs))

For this example, we’re exploring how the help() function can provide information about built-in functions in Python. First, we use print() to display a header indicating that we’re looking at the Python len function. Then, by calling help(len), we’re actually invoking the help documentation for the len() function. This documentation provides insights into how the len() function works, its parameters, and its purpose.

After that, we create another header, this time for the abs function, using print(). By calling help(abs), we’re fetching the documentation for the abs() built-in function. This will give us a detailed understanding of how the abs() function operates and what it’s used for.

Output
Python len function:

Help on built-in function len in module builtins:

len(obj, /)
Return the number of items in a container.

None


Python len function:

Help on built-in function abs in module builtins:

abs(x, /)
Return the absolute value of the argument.

None

In summary, this code showcases how you can use the help() function to access and display information about different built-in functions in Python, helping you better understand their usage and functionality.

II. Discovering Module Functions

You can use Python help() with a module as an argument to investigate the functions, classes, and attributes provided within that module. For example, invoking help(math) will present you with the documentation related to the math module, showcasing its functionalities and components. Take a look at a code mentioned below.

Example Code
# Let's get help for the 'math' module import math help(math)

In this example, we’re on a journey to uncover insights about the ‘math‘ module. We’ve embarked on this exploration by first importing the ‘math‘ module using the import statement. Now, we’re taking a moment to utilize the help() function to gain a deeper understanding of what the ‘math‘ module has to offer. By doing this, we’re accessing comprehensive documentation that sheds light on the functions, classes, and attributes within the ‘math‘ module.

Output
Help on built-in module math:

NAME
math

DESCRIPTION
This module provides access to the mathematical functions
defined by the C standard.

FUNCTIONS
acos(x, /)
Return the arc cosine (measured in radians) of x.

The result is between 0 and pi.

acosh(x, /)
Return the inverse hyperbolic cosine of x.

asin(x, /)
Return the arc sine (measured in radians) of x.

The result is between -pi/2 and pi/2.

asinh(x, /)
Return the inverse hyperbolic sine of x.

atan(x, /)
Return the arc tangent (measured in radians) of x.

The result is between -pi/2 and pi/2.

atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x.

Unlike atan(y/x), the signs of both x and y are considered.

atanh(x, /)
Return the inverse hyperbolic tangent of x.

ceil(x, /)
Return the ceiling of x as an Integral.

This is the smallest integer >= x.

comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order.

Evaluates to n! / (k! * (n – k)!) when k <= n and evaluates
to zero when k > n.

Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n.

Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.

copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y.

On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0.

cos(x, /)
Return the cosine of x (measured in radians).

cosh(x, /)
Return the hyperbolic cosine of x.

degrees(x, /)
Convert angle x from radians to degrees.

dist(p, q, /)
Return the Euclidean distance between two points p and q.

The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension.

Roughly equivalent to:
sqrt(sum((px – qx) ** 2.0 for px, qx in zip(p, q)))

erf(x, /)
Error function at x.

erfc(x, /)
Complementary error function at x.

exp(x, /)
Return e raised to the power of x.

expm1(x, /)
Return exp(x)-1.

This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.

fabs(x, /)
Return the absolute value of the float x.

factorial(x, /)
Find x!.

Raise a ValueError if x is negative or non-integral.

floor(x, /)
Return the floor of x as an Integral.

This is the largest integer <= x.

fmod(x, y, /)
Return fmod(x, y), according to platform C.

x % y may differ.

frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e).

m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.

fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq.

Assumes IEEE-754 floating point arithmetic.

gamma(x, /)
Gamma function at x.

gcd(*integers)
Greatest Common Divisor.

hypot(…)
hypot(*coordinates) -> value

Multidimensional Euclidean distance from the origin to a point.

Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates))

For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y).

For example, the hypotenuse of a 3/4/5 right triangle is:

>>> hypot(3.0, 4.0)
5.0

isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value.

rel_tol
maximum difference for being considered “close”, relative to the
magnitude of the input values
abs_tol
maximum difference for being considered “close”, regardless of the
magnitude of the input values

Return True if a is close in value to b, and False otherwise.

For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances.

-inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves.

isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise.

isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise.

isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise.

isqrt(n, /)
Return the integer part of the square root of the input.

lcm(*integers)
Least Common Multiple.

ldexp(x, i, /)
Return x * (2**i).

This is essentially the inverse of frexp().

lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x.

log(…)
log(x, [base=math.e])
Return the logarithm of x to the given base.

If the base not specified, returns the natural logarithm (base e) of x.

log10(x, /)
Return the base 10 logarithm of x.

log1p(x, /)
Return the natural logarithm of 1+x (base e).

The result is computed in a way which is accurate for x near zero.

log2(x, /)
Return the base 2 logarithm of x.

modf(x, /)
Return the fractional and integer parts of x.

Both results carry the sign of x and are floats.

nextafter(x, y, /)
Return the next floating-point value after x towards y.

perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order.

Evaluates to n! / (n – k)! when k <= n and evaluates
to zero when k > n.

If k is not specified or is None, then k defaults to n
and the function returns n!.

Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative.

pow(x, y, /)
Return x**y (x to the power of y).

prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable.

The default start value for the product is 1.

When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject
non-numeric types.

radians(x, /)
Convert angle x from degrees to radians.

remainder(x, y, /)
Difference between x and the closest integer multiple of y.

Return x – n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact.

sin(x, /)
Return the sine of x (measured in radians).

sinh(x, /)
Return the hyperbolic sine of x.

sqrt(x, /)
Return the square root of x.

tan(x, /)
Return the tangent of x (measured in radians).

tanh(x, /)
Return the hyperbolic tangent of x.

trunc(x, /)
Truncates the Real x to the nearest Integral toward 0.

Uses the __trunc__ magic method.

ulp(x, /)
Return the value of the least significant bit of the float x.

DATA
e = 2.718281828459045
inf = inf
nan = nan
pi = 3.141592653589793
tau = 6.283185307179586

FILE
(built-in)

As you can see in the above example by using help() function you can easily access the documentation of python’s module.

III. Understanding Class Methods

Using the help() function on a class, it opens up a wealth of information about the methods and attributes associated with that class. This approach grants you valuable insights into the functionalities and possibilities that the class offers. Consider the following example:

Example Code
class Car: """A simple class representing a car.""" def __init__(self, make, model, year): self.make = make self.model = model self.year = year def start_engine(self): """Starts the car's engine.""" print(f"{self.make} {self.model}'s engine is now running.") def stop_engine(self): """Stops the car's engine.""" print(f"{self.make} {self.model}'s engine has been turned off.") help(Car)

Here, we’ve created a class called Car. This class is a blueprint for creating car objects in Python. It has a constructor method, __init__(), which initializes the car’s attributes such as make, model, and year.

The Car class also includes two additional methods, start_engine() and stop_engine(), which simulate starting and stopping the car’s engine. These methods utilize the car’s attributes to provide meaningful output messages.

By using the help() function on the Car class, we’re able to access detailed information about the class, including its docstring, attributes, and methods. This allows us to understand the purpose of the class and how to interact with it. Running the code will display the class’s docstring and method descriptions, giving us insights into its functionalities.

Output
class Car(builtins.object)
| Car(make, model, year)
|
| A simple class representing a car.
|
| Methods defined here:
|
| __init__(self, make, model, year)
| Initialize self. See help(type(self)) for accurate signature.
|
| start_engine(self)
| Starts the car’s engine.
|
| stop_engine(self)
| Stops the car’s engine.
|
| ———————————————————————-
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)

Overall, this example illustrates how the help() function can be used to gain deeper insights into the attributes and methods of a class, helping you to utilize the class efficiently in our code.

IV. Exploring Object Methods

Upon the working of  help() with an object instance, you can uncover details regarding the attributes that pertain to that particular object. For instance, consider the following scenario:

Example Code
my_tuple=("Python","Java","React") print(help(my_tuple))

Here, we’re using the help() function to gather information about the my_tuple object, which contains three elements: Python, Java, and React. When we execute the code, the help() function provides us with details about the tuple object, its methods, and attributes. It’s essentially like peeking into the user manual for tuples in Python. Keep in mind that the exact output you see may vary based on your Python version, but generally, it will display information about tuple methods and properties that can be useful for working with tuples.

Output
Help on tuple object:

class tuple(object)
| tuple(iterable=(), /)
|
| Built-in immutable sequence.
|
| If no argument is given, the constructor returns an empty tuple.
| If iterable is specified the tuple is initialized from iterable’s items.
|
| If the argument is a tuple, the return value is the same object.
|
| Built-in subclasses:
| asyncgen_hooks
| UnraisableHookArgs
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(self, key, /)
| Return self[key].
|
| __getnewargs__(self, /)
|
| __gt__(self, value, /)
| Return self>value.
|
| __hash__(self, /)
| Return hash(self).
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __rmul__(self, value, /)
| Return value*self.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| ———————————————————————-
| Class methods defined here:
|
| __class_getitem__(…) from builtins.type
| See PEP 585
|
| ———————————————————————-
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.

As you can see, using the help() function on the my_tuple object gives you valuable insights and helping you to make the most of tuples in Python programming.

Python help() Advanced Examples

In the following section, we will examine several advanced examples of Python help() function, highlighting its flexibility and wide range of applications.

I. Using help() in Interactive Environments

Python help() is particularly valuable in interactive environments like the Python shell. When you are unsure about a specific function or need more information while writing your code, you can quickly use help() to get insights without leaving your development environment. Here’s an example of how you might use the help() function in an interactive environment.

The initial step involves using an interactive environment. To clarify, please follow these outlined steps, which will allow you to observe its functionality within that context:

  • Open your terminal or command prompt and start an interactive Python session by typing python and hitting Enter.
  • In the interactive Python shell, type help(print) and press Enter. This will display the help documentation for the print() function.
  • Once you press Enter, you’ll see detailed information about the print() function displayed on your screen. This information includes a description of what the function does, the syntax to use it, and any parameters it accepts.
  • Depending on your terminal’s capabilities, you might need to scroll through the documentation using your keyboard’s arrow keys or other navigation keys. The help documentation might be quite extensive, so take your time to read through it.
  • To exit the help viewer and return to the interactive Python shell, press the q key.
  • After you press Enter, you’ll see the help documentation for the print() function, which will provide you with information about its usage, parameters, and more.

Here’s a simplified example of what you would see in your terminal:

Output
Python 3.8.2 (default, Feb 26 2020, 02:56:10)
[GCC 4.2.1 Compatible Apple LLVM 11.0.3 (clang-1103.0.29.20) (-macos10.15-objc-s
utf-8) on darwin
Type “help”, “copyright”, “credits” or “license” for more information.
>>> help(print)

Remember, you can use the help() function in the same way with other functions, modules, and objects in Python to access their documentation.

II. Python help() and dir() Function

Having explored the scenarios mentioned above, you now have a clear understanding of the help() function and how it can be employed in your Python programs. Moving forward, it’s essential to grasp the distinction between the help() and dir() functions. Let’s delve into this difference to enhance your comprehension.

A. Python help() Function

You’re already familiar with the help() function, a built-in tool in Python’s toolkit used to offer insights into classes, functions, and modules. Now, let’s explore an example that will help you differentiate it from the dir() function.

Example Code
# Example variable even_numbers = [2, 4, 6, 8, 10] # Using help() to get information about the list help(even_numbers)

In this example, we have defined a variable named even_numbers, which holds a list of even numbers. The given values consist of [2, 4, 6, 8, 10]. Next, we’re using the help() function to retrieve information about the even_numbers list. When the help(even_numbers) line is executed, Python’s built-in help system will provide us with details about the list’s properties, methods, and functions.

Output
Help on list object:

class list(object)
| list(iterable=(), /)
|
| Built-in mutable sequence.
|
| If no argument is given, the constructor creates a new empty list.
| The argument must be an iterable if specified.
|
| Methods defined here:
|
| __add__(self, value, /)
| Return self+value.
|
| __contains__(self, key, /)
| Return key in self.
|
| __delitem__(self, key, /)
| Delete self[key].
|
| __eq__(self, value, /)
| Return self==value.
|
| __ge__(self, value, /)
| Return self>=value.
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __getitem__(…)
| x.__getitem__(y) <==> x[y]
|
| __gt__(self, value, /)
| Return self>value.
|
| __iadd__(self, value, /)
| Implement self+=value.
|
| __imul__(self, value, /)
| Implement self*=value.
|
| __init__(self, /, *args, **kwargs)
| Initialize self. See help(type(self)) for accurate signature.
|
| __iter__(self, /)
| Implement iter(self).
|
| __le__(self, value, /)
| Return self<=value.
|
| __len__(self, /)
| Return len(self).
|
| __lt__(self, value, /)
| Return self<value.
|
| __mul__(self, value, /)
| Return self*value.
|
| __ne__(self, value, /)
| Return self!=value.
|
| __repr__(self, /)
| Return repr(self).
|
| __reversed__(self, /)
| Return a reverse iterator over the list.
|
| __rmul__(self, value, /)
| Return value*self.
|
| __setitem__(self, key, value, /)
| Set self[key] to value.
|
| __sizeof__(self, /)
| Return the size of the list in memory, in bytes.
|
| append(self, object, /)
| Append object to the end of the list.
|
| clear(self, /)
| Remove all items from list.
|
| copy(self, /)
| Return a shallow copy of the list.
|
| count(self, value, /)
| Return number of occurrences of value.
|
| extend(self, iterable, /)
| Extend list by appending elements from the iterable.
|
| index(self, value, start=0, stop=9223372036854775807, /)
| Return first index of value.
|
| Raises ValueError if the value is not present.
|
| insert(self, index, object, /)
| Insert object before index.
|
| pop(self, index=-1, /)
| Remove and return item at index (default last).
|
| Raises IndexError if list is empty or index is out of range.
|
| remove(self, value, /)
| Remove first occurrence of value.
|
| Raises ValueError if the value is not present.
|
| reverse(self, /)
| Reverse *IN PLACE*.
|
| sort(self, /, *, key=None, reverse=False)
| Sort the list in ascending order and return None.
|
| The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
| order of two equal elements is maintained).
|
| If a key function is given, apply it once to each list item and sort them,
| ascending or descending, according to their function values.
|
| The reverse flag can be set to sort in descending order.
|
| ———————————————————————-
| Class methods defined here:
|
| __class_getitem__(…) from builtins.type
| See PEP 585
|
| ———————————————————————-
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
|
| ———————————————————————-
| Data and other attributes defined here:
|
| __hash__ = None

It’s a convenient way to learn more about the capabilities of the even_numbers list without having to consult external documentation.

B. Python dir() Function

The dir() function in Python lets you see a list of attributes and methods of an object. It shows you what functionalities you can use with the object, both built-in and user-defined. It’s a quick way to explore an object’s capabilities without looking up external documentation. Consider the following example:

Example Code
prime_numbers = [2, 3, 5, 7, 11] print(dir(prime_numbers))

For this example, we’ve created a list named prime_numbers containing some prime numbers. Then, we’re using the dir() function to inspect and display the attributes and methods associated with the prime_numbers list. This provides us with a glimpse of all the functionalities we can use with lists in Python. By using dir() in this way, we can explore the available operations and methods that can be applied to the prime_numbers list, helping us better understand its potential uses.

Output
[‘__add__’, ‘__class__’, ‘__class_getitem__’, ‘__contains__’, ‘__delattr__’, ‘__delitem__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__gt__’, ‘__hash__’, ‘__iadd__’, ‘__imul__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__reversed__’, ‘__rmul__’, ‘__setattr__’, ‘__setitem__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘append’, ‘clear’, ‘copy’, ‘count’, ‘extend’, ‘index’, ‘insert’, ‘pop’, ‘remove’, ‘reverse’, ‘sort’]

By using this approach you can easily discover the rich set of capabilities that the prime_numbers list offers.

III. Handling Exceptions and Errors with help()

It’s important to know how to deal with situations where help() might not provide information. Sometimes, you might encounter situations where the object you pass to help() doesn’t have any associated documentation, or it might raise an error. Handling such exceptions gracefully will ensure your code runs smoothly. For instance:

Example Code
try: help("python") except TypeError as e: print(f"Error: {e}")

Here, we’re trying to use the help() function on a string python. However, the help() function can only be used on specific types of objects like modules, classes, methods, functions, or traceback objects. Since python is not one of these allowable types, it raises a TypeError. In the except block, we catch this error and print out a message to indicate that help() is not used for these type of objects.

Output
No Python documentation found for ‘python’.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

This example highlights how using the help() function on inappropriate types of objects can lead to exceptions, and it’s important to handle such situations gracefully in your code.

IV. Exploring Python Libraries with help()

Python has an extensive standard library, as well as countless third-party libraries. Using help() to explore these libraries can give you deep insights into their functionalities, allowing you to leverage their capabilities efficiently in your projects. Consider the following example:

Example Code
# Using help() to explore the 'random' library import random help(random)

In this example, we’re illustrating how to utilize the help() function to explore the functionalities of the built-in Python library called ‘random’. By importing the random module, we gain access to various random number generation functions and methods. When we pass random as an argument to the help() function, it displays detailed information about the library’s functions, classes, and other attributes.

Output
Help on module random:

NAME
random – Random variable generators.

MODULE REFERENCE
https://docs.python.org/3.10/library/random.html

The following documentation is automatically generated from the Python
source files. It may be incomplete, incorrect or include features that
are considered implementation detail and may vary between Python
implementations. When in doubt, consult the module reference at the
location listed above.

DESCRIPTION
bytes
—–
uniform bytes (values between 0 and 255)

integers
——–
uniform within range

sequences
———
pick random element
pick random sample
pick weighted random sample
generate random permutation

distributions on the real line:
——————————
uniform
triangular
normal (Gaussian)
lognormal
negative exponential
gamma
beta
pareto
Weibull

distributions on the circle (angles 0 to 2pi)
———————————————
circular uniform
von Mises

General notes on the underlying Mersenne Twister core generator:

* The period is 2**19937-1.
* It is one of the most extensively tested generators in existence.
* The random() method is implemented in C, executes in a single Python step,
and is, therefore, threadsafe.

CLASSES
_random.Random(builtins.object)
Random
SystemRandom

class Random(_random.Random)
| Random(x=None)
|
| Random number generator base class used by bound module functions.
|
| Used to instantiate 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: in that case, override the following
| methods: random(), seed(), getstate(), and setstate().
| Optionally, implement a getrandbits() method so that randrange()
| can cover arbitrarily large ranges.
|
| Method resolution order:
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since random was
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| 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.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha – 1) * math.exp(-x / beta)
| pdf(x) = ————————————–
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| getstate(self)
| Return internal state; can be passed to setstate() later.
|
| lognormvariate(self, 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.
|
| normalvariate(self, mu, sigma)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randbytes(self, n)
| Generate n random bytes.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence or set.
|
| 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
| 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 range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| seed(self, a=None, version=2)
| Initialize internal state from a seed.
|
| The only supported seed types are None, int, float,
| str, bytes, and bytearray.
|
| None or no argument seeds from current time or from an operating
| system specific randomness source if available.
|
| If *a* is an int, all bits are used.
|
| For version 2 (the default), all of the bits are used if *a* is a str,
| bytes, or bytearray. For version 1 (provided for reproducing random
| sequences from older versions of Python), the algorithm for str and
| bytes generates a narrower range of seeds.
|
| setstate(self, state)
| Restore internal state from object returned by getstate().
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| 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.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ———————————————————————-
| Class methods defined here:
|
| __init_subclass__(**kwargs) from builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ———————————————————————-
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ———————————————————————-
| Data and other attributes defined here:
|
| VERSION = 3
|
| ———————————————————————-
| Methods inherited from _random.Random:
|
| getrandbits(self, k, /)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| random(self, /)
| random() -> x in the interval [0, 1).
|
| ———————————————————————-
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.

class SystemRandom(Random)
| SystemRandom(x=None)
|
| Alternate random number generator using sources provided
| by the operating system (such as /dev/urandom on Unix or
| CryptGenRandom on Windows).
|
| Not available on all systems (see os.urandom() for details).
|
| Method resolution order:
| SystemRandom
| Random
| _random.Random
| builtins.object
|
| Methods defined here:
|
| getrandbits(self, k)
| getrandbits(k) -> x. Generates an int with k random bits.
|
| getstate = _notimplemented(self, *args, **kwds)
|
| randbytes(self, n)
| Generate n random bytes.
|
| random(self)
| Get the next random number in the range [0.0, 1.0).
|
| seed(self, *args, **kwds)
| Stub method. Not used for a system random number generator.
|
| setstate = _notimplemented(self, *args, **kwds)
|
| ———————————————————————-
| Methods inherited from Random:
|
| __getstate__(self)
| # Issue 17489: Since __reduce__ was defined to fix #759889 this is no
| # longer called; we leave it here because it has been here since random was
| # rewritten back in 2001 and why risk breaking something.
|
| __init__(self, x=None)
| Initialize an instance.
|
| Optional argument x controls seeding, as for Random.seed().
|
| __reduce__(self)
| Helper for pickle.
|
| __setstate__(self, state)
|
| betavariate(self, alpha, beta)
| Beta distribution.
|
| Conditions on the parameters are alpha > 0 and beta > 0.
| Returned values range between 0 and 1.
|
| choice(self, seq)
| Choose a random element from a non-empty sequence.
|
| choices(self, population, weights=None, *, cum_weights=None, k=1)
| Return a k sized list of population elements chosen with replacement.
|
| If the relative weights or cumulative weights are not specified,
| the selections are made with equal probability.
|
| expovariate(self, lambd)
| 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.
|
| gammavariate(self, alpha, beta)
| Gamma distribution. Not the gamma function!
|
| Conditions on the parameters are alpha > 0 and beta > 0.
|
| The probability distribution function is:
|
| x ** (alpha – 1) * math.exp(-x / beta)
| pdf(x) = ————————————–
| math.gamma(alpha) * beta ** alpha
|
| gauss(self, mu, sigma)
| Gaussian distribution.
|
| mu is the mean, and sigma is the standard deviation. This is
| slightly faster than the normalvariate() function.
|
| Not thread-safe without a lock around calls.
|
| lognormvariate(self, 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.
|
| normalvariate(self, mu, sigma)
| Normal distribution.
|
| mu is the mean, and sigma is the standard deviation.
|
| paretovariate(self, alpha)
| Pareto distribution. alpha is the shape parameter.
|
| randint(self, a, b)
| Return random integer in range [a, b], including both end points.
|
| randrange(self, start, stop=None, step=1)
| Choose a random item from range(start, stop[, step]).
|
| This fixes the problem with randint() which includes the
| endpoint; in Python this is usually not what you want.
|
| sample(self, population, k, *, counts=None)
| Chooses k unique random elements from a population sequence or set.
|
| 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
| 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 range() for the
| population argument. This is especially fast and space efficient
| for sampling from a large population:
|
| sample(range(10000000), 60)
|
| shuffle(self, x, random=None)
| Shuffle list x in place, and return None.
|
| Optional argument random is a 0-argument function returning a
| random float in [0.0, 1.0); if it is the default None, the
| standard random.random will be used.
|
| triangular(self, low=0.0, high=1.0, mode=None)
| Triangular distribution.
|
| Continuous distribution bounded by given lower and upper limits,
| and having a given mode value in-between.
|
| http://en.wikipedia.org/wiki/Triangular_distribution
|
| uniform(self, a, b)
| Get a random number in the range [a, b) or [a, b] depending on rounding.
|
| vonmisesvariate(self, mu, kappa)
| Circular data distribution.
|
| 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.
|
| weibullvariate(self, alpha, beta)
| Weibull distribution.
|
| alpha is the scale parameter and beta is the shape parameter.
|
| ———————————————————————-
| Class methods inherited from Random:
|
| __init_subclass__(**kwargs) from builtins.type
| Control how subclasses generate random integers.
|
| The algorithm a subclass can use depends on the random() and/or
| getrandbits() implementation available to it and determines
| whether it can generate random integers from arbitrarily large
| ranges.
|
| ———————————————————————-
| Data descriptors inherited from Random:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
|
| ———————————————————————-
| Data and other attributes inherited from Random:
|
| VERSION = 3
|
| ———————————————————————-
| Static methods inherited from _random.Random:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.

FUNCTIONS
betavariate(alpha, beta) method of Random instance
Beta distribution.

Conditions on the parameters are alpha > 0 and beta > 0.
Returned values range between 0 and 1.

choice(seq) method of Random instance
Choose a random element from a non-empty sequence.

choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance
Return a k sized list of population elements chosen with replacement.

If the relative weights or cumulative weights are not specified,
the selections are made with equal probability.

expovariate(lambd) method of Random instance
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.

gammavariate(alpha, beta) method of Random instance
Gamma distribution. Not the gamma function!

Conditions on the parameters are alpha > 0 and beta > 0.

The probability distribution function is:

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

gauss(mu, sigma) method of Random instance
Gaussian distribution.

mu is the mean, and sigma is the standard deviation. This is
slightly faster than the normalvariate() function.

Not thread-safe without a lock around calls.

getrandbits(k, /) method of Random instance
getrandbits(k) -> x. Generates an int with k random bits.

getstate() method of Random instance
Return internal state; can be passed to setstate() later.

lognormvariate(mu, sigma) method of Random instance
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.

normalvariate(mu, sigma) method of Random instance
Normal distribution.

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

paretovariate(alpha) method of Random instance
Pareto distribution. alpha is the shape parameter.

randbytes(n) method of Random instance
Generate n random bytes.

randint(a, b) method of Random instance
Return random integer in range [a, b], including both end points.

random() method of Random instance
random() -> x in the interval [0, 1).

randrange(start, stop=None, step=1) method of Random instance
Choose a random item from range(start, stop[, step]).

This fixes the problem with randint() which includes the
endpoint; in Python this is usually not what you want.

sample(population, k, *, counts=None) method of Random instance
Chooses k unique random elements from a population sequence or set.

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
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 range() for the
population argument. This is especially fast and space efficient
for sampling from a large population:

sample(range(10000000), 60)

seed(a=None, version=2) method of Random instance
Initialize internal state from a seed.

The only supported seed types are None, int, float,
str, bytes, and bytearray.

None or no argument seeds from current time or from an operating
system specific randomness source if available.

If *a* is an int, all bits are used.

For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.

setstate(state) method of Random instance
Restore internal state from object returned by getstate().

shuffle(x, random=None) method of Random instance
Shuffle list x in place, and return None.

Optional argument random is a 0-argument function returning a
random float in [0.0, 1.0); if it is the default None, the
standard random.random will be used.

triangular(low=0.0, high=1.0, mode=None) method of Random instance
Triangular distribution.

Continuous distribution bounded by given lower and upper limits,
and having a given mode value in-between.

http://en.wikipedia.org/wiki/Triangular_distribution

uniform(a, b) method of Random instance
Get a random number in the range [a, b) or [a, b] depending on rounding.

vonmisesvariate(mu, kappa) method of Random instance
Circular data distribution.

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.

weibullvariate(alpha, beta) method of Random instance
Weibull distribution.

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

DATA
__all__ = [‘Random’, ‘SystemRandom’, ‘betavariate’, ‘choice’, ‘choices…

FILE
c:\program files\windowsapps\pythonsoftwarefoundation.python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\random.py

This allows you to understand and use the capabilities of the random library effectively in our code.

Having gained a thorough understanding of Python help() function, its applications, and its adaptability in diverse situations, you now possess a solid groundwork. To enhance your understanding, let’s delve into some theoretical concepts that will prove incredibly valuable on your Python programming journey.

Limitations of the help() Function

While you’re using the help() function to explore Python objects and libraries, it’s important to be aware of its limitations:

I. Availability of Documentation

The effectiveness of help() depends on the presence and quality of documentation for the objects you are exploring. Some objects may lack comprehensive documentation, making it challenging to get detailed information.

II. External Libraries

The help() primarily provides you a documentation for Python’s built-in functions, modules, and classes. It may not always offer insights into third-party libraries that have not included detailed docstrings.

III. Limited Context

The output from help() is often extensive, displaying a lot of information that may not be immediately relevant to your specific use case. You may need to spend some time filtering through the output to find the relevant details.

Practical Use Cases of the help() Function

Despite its limitations, you’ll find the help() function to be incredibly useful in various real-world situations.

I. Learning Python

If you’re a beginner, Python help() is a fantastic tool for understanding Python’s built-in functions, modules, and classes. It’s a convenient way to explore the language’s features and gain practical insights.

II. Module Exploration

Python help() helps you understand the available functions, classes, and attributes, enabling you to leverage the module’s capabilities effectively.

III. API Reference

In larger projects or when collaborating with others, you can use help() as an internal API reference. This allows team members to quickly grasp the code and its various components.

Congratulations on completing this Python helper tutorial on Pythonhelp() function! It’s like having a personal guide to Python’s vast landscape. With help(), you’ve unlocked a treasure trove of information about modules, functions, classes, methods, and even keywords. This built-in interactive helper is your compass in the Python universe.

By now, you’re familiar with the help() function’s syntax and parameters, crucial knowledge for your Python journey. Armed with this understanding, you’re equipped to make the most out of its potential in different scenarios. Remember, mastering the syntax opens doors to harnessing its capabilities effectively.

And not only this through this Python Helper guide you learned the creation of the help() Object, you learn how to get built for functions, modules, class methods , object methods and even you explore that you can also use it in an interactive environment and last but not the least you also discover the functionalities of python help() with dir() function.

Furthermore , you observes the limitations of help() function but don’t worry about this there are more things which is very helpful to you in your python coding journey. So, remember, you’re not alone on this journey. With help() by your side, Python’s secrets are at your fingertips. Keep coding, keep exploring, and let the knowledge flow. Your Python adventure is just beginning! Happy coding!

 
Scroll to Top