The Wayback Machine - https://web.archive.org/web/20250120092124/https://www.geeksforgeeks.org/help-function-in-python/
Open In App

Help function in Python

Last Updated : 20 Jun, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, the help() function is a built-in function that provides information about modules, classes, functions, and modules. In this article, we will learn about help function in Python.

help() function in Python Syntax

Syntax: help([object])

Parameters (Optional) : Any object for which we want some help or the information.

If the help function is passed without an argument, then the interactive help utility starts up on the console.

What is Help function in Python?

The Python help function is used to display the documentation of modules, functions, classes, keywords, etc. It provides information about modules, classes, functions, and methods. It is a useful tool for getting documentation and assistance on various aspects of Python. 

Python help() function Examples

Simple help() Program

In this example, we are using help() without any object to access documentation in Python.

Python
help()

Output
Welcome to Python 3.7'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.7/tutorial/.

Enter the name ...


Help with Print Function in Python

Let us check the documentation of the print function in the Python console.

Python
help(print)

Output

Help on built-in function print in module builtins:
print(...)
print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.

Help on User Defined Class in Python

Help function output can also be defined for user-defined functions and classes. The docstring(documentation string) is used for documentation. It is nested inside triple quotes and is the first statement within a class or function or a module. Let us define a class with functions.

Python
class Helper:
    def __init__(self):
        '''The helper class is initialized'''

    def print_help(self):
        '''Returns the help description'''
        print('helper description')


help(Helper)
help(Helper.print_help)

Output 

Help on class Helper in module __main__:
class Helper(builtins.object)
| Methods defined here:
|
| __init__(self)
| The helper class is initialized
|
| print_help(self)
| Returns the help description
|
| ----------------------------------------------------------------------
| Data descriptors defined here:
|
| __dict__
| dictionary for instance variables (if defined)
|
| __weakref__
| list of weak references to the object (if defined)
Help on function print_help in module __main__:
print_help(self)
Returns the help description

If no Help or Info is Present

In this example, we are using help() if no help or info is present and access documentation in Python.

Python
print(help("GeeksforGeeks"))

Output
No Python documentation found for 'GeeksforGeeks'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.

None



If a string is given as an argument

In this example, we are passing a string inside the help function to access documentation in Python.

Python
help('gfg')

Output
No Python documentation found for 'gfg'.
Use help() to get the interactive help utility.
Use help(str) for help on the str class.




Python help() function docstring

The docstrings are declared using ”’triple single quotes”’ or “””triple double quotes””” just below the class, method or function declaration. All functions should have a docstring.

Accessing Docstrings: The docstrings can be accessed using the __doc__ method of the object or using the help function.

Python
def my_function():
    '''Demonstrates triple double quotes
    docstrings and does nothing really.'''

    return None

print("Using __doc__:")
print(my_function.__doc__)

print("Using help:")
help(my_function)

Output
Using __doc__:
Demonstrates triple double quotes
    docstrings and does nothing really.
Using help:
Help on function my_function in module __main__:

my_function()
    Demonstrates triple double quot...


Help function in Python – FAQs

How to handle unexpected exception in Python?

To handle unexpected exceptions in Python, you can use a try-except block with a generic Exception class or BaseException as the exception type. This will catch any exception that occurs within the try block.

try:
# Code that might raise an exception
result = 10 / 0 # Example of a division by zero which raises an exception
except Exception as e:
print("An unexpected error occurred:", str(e))
# Handle the exception gracefully, log it, or take appropriate action

How to handle exceptions inside a class in Python?

To handle exceptions inside a class in Python, you can use try-except blocks within methods of the class.

class MyClass:
def method_with_exception(self):
try:
# Code that might raise an exception
result = 10 / 0 # Example of a division by zero which raises an exception
except ZeroDivisionError as e:
print("Division by zero error:", str(e))
# Handle the specific exception
except Exception as e:
print("An unexpected error occurred:", str(e))
# Handle any other exceptions

# Example usage:
obj = MyClass()
obj.method_with_exception()

How to pass an exception in Python?

In Python, you can raise an exception using the raise statement. This allows you to indicate that an exceptional situation has occurred within your code.

def validate_age(age):
if age < 0:
raise ValueError("Age cannot be negative")
# Example usage:
try:
validate_age(-5)
except ValueError as e:
print("Invalid age input:", str(e))
# Handle the raised exception

How to catch an unknown exception in Python?

To catch an unknown or unexpected exception in Python, you can use a catch-all except block without specifying a specific exception type. This will handle any exception that occurs within the try block.

try:
# Code that might raise an exception
result = 10 / 0 # Example of a division by zero which raises an exception
except Exception as e:
print("An unknown or unexpected error occurred:", str(e))
# Handle the exception gracefully, log it, or take appropriate action

Is the finally block always executed?

Yes, the finally block in a try-except-finally statement is always executed, regardless of whether an exception was raised or not. It is typically used to perform cleanup actions such as closing files or releasing resources that were opened or acquired in the try block.

try:
# Code that might raise an exception
file = open('example.txt', 'r')
result = 10 / 0 # Example of a division by zero which raises an exception
except ZeroDivisionError as e:
print("Division by zero error:", str(e))
# Handle specific exception
except Exception as e:
print("An unexpected error occurred:", str(e))
# Handle any other exceptions
finally:
print("Closing file")
file.close() # This will always execute, even if an exception was raised


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg