DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
What's in store for DevOps in 2023? Hear from the experts in our "DZone 2023 Preview: DevOps Edition" on Fri, Jan 27!
Save your seat
  1. DZone
  2. Coding
  3. Languages
  4. Getting Help From the Python Interpreter

Getting Help From the Python Interpreter

Python is a powerful and popular language for big data and data science. If you're new to Python or need a refresher, read on to learn!

Gaurav Gahlot user avatar by
Gaurav Gahlot
·
Oct. 29, 18 · Tutorial
Like (7)
Save
Tweet
Share
7.68K Views

Join the DZone community and get the full member experience.

Join For Free

Whether we want some help for a module or want to quickly test a piece of code, the Python interpreter is of great help. I this article, we are going to cover different ways that the Python interpreter comes handy. In previous articles we have:

  • Set up Python environment on Linux-based systems.
  • Set up Python environment on Windows,
  • Run our first Python script,

So, what are you waiting for? Start your interpreter and follow along as we talk about:

  • Getting help from the interpreter.
  • Import a module.
  • Listing all the available modules.
  • Executing some Python code.

Let's get started!

help()

The very first helpful function that I want to talk about is the builtin help() function. It comes from the __builtins__ module and is of great help. There are two ways to use help — interactive help and the help about object.

Interactive Help

To start, make sure that you have the interpreter ready. Now, type help() and press the return key. You should now see a screen similar to this one:

Interactive help from Python Interpreter

The help> shows that our interactive help is ready to help us. Now we can use it to get help for different modules and functions. Let's give it a try, and search for math and math.pow as shown below:

help> math

Help on module math:

NAME
    math

MODULE REFERENCE
    https://docs.python.org/3.7/library/math    
    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
    This module is always available.  It provides access to the
    mathematical functions defined by the C standard.

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

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


help> math.pow

Help on built-in function pow in math:

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

We can exit the help document and the interactive help by pressing the q key and then pressing the return key.

Help About Object

We often want quick help on some module rather than entering the interactive help, and that's where the help about object comes in handy. So, when our interpreter is ready we can get help about a module or function by using the help(<object>) function.

To get help for math.pow we first need to import the math module and ask for help with the pow function. Please refer the code below:

>>> import math
>>> help(math.pow)
Help on built-in function pow in math:

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

Please note that we have to import the math module first, otherwise, we get an error as shown below:

>>> help(math.pow)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined

There is one more way to get help on a specific module. We can find all the available modules using the help("modules") function call. And it would return a result something like this:

help(&quot;modules&quot;)

It is obvious that the list shown in the image above is not complete. Okay, now that we know about the available modules, we can get help on them and this time we are not even going to import one.

Yes, we can get the details of a module without importing it, and to do so we use the help("module_name") function, as shown below:

>>> help("flask")

Help on package flask:

NAME
    flask

DESCRIPTION
    flask
    ~~~~~

    A microframework based on Werkzeug.  It's extensively documented
    and follows best practice patterns.

    :copyright: © 2010 by the Pallets team.
    :license: BSD, see LICENSE for more details.

PACKAGE CONTENTS
    __main__
    _compat
    app
...

import

The import command helps you to import a module that is not currently available. By default, commonly used modules like math, random, web, datetime, etc., are not available and ready to use. To use these modules or any other module we first need to import that module and then use it. You can do so simply  byusing the import <module> command, as we did earlier with our help function.

Think of a scenario where you have installed flask, however, while running your app you are getting ModuleNotFoundError. That's where import command comes to rescue. If the module import is successful, nothing is returned from the command. But if the import fails, we get an error as shown below:

>>> import math   #successful import
>>> import flask  #import fails
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'flask'

dir()

Another helpful function that I want to talk about is the builtin dir() function. Similar to the dir command on Windows/DOS, the dir function, when called without an argument, returns you the names of different modules in the current scope.

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>>
>>>

When used with an object, it returns an alphabetized list of names comprising (some of) the attributes of the given object, and of attributes reachable from it. The help(dir) defines it as:

If the object supplies a method named __dir__, it will be used; otherwise the default dir() logic is used and returns:
        for a module object: the module's attributes.
        for a class object: its attributes, and recursively the attributes of its         bases.
        for any other object: its attributes, its class's attributes, and         recursively the attributes of its class's base classes.

The image below shows the result of dir(__builtins__) function call:

dir(__builtins__)

When we import any module, say math module, then we can see those modules in the response or result of the dir() function. Also, if we have some objects created in that scope then we will see those objects as well.

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'math', 'numbers', 'os', 'random']
>>>
>>>

Executing Code

Now that we understand how to get help from the interpreter, it's time to see how we can use that help and execute some code for quick testing. So, let's create a list of integers and then print the square of each number using the math.pow function.

Let's start the Python interpreter and create a list of integers and assign it to the variable numbers:

>>> numbers = [1, 2, 3, 4, 5]
>>> type(numbers)
<class 'list'>
>>>

The type(numbers) function returns the type of the variable or object reference. Let's now import the math module, iterate over the list of numbers, and print the square of each one, as shown in the code below:

>>> import math
>>> for number in numbers:
...     square = math.pow(number, 2)
...     print(square)
... 
1.0
4.0
9.0
16.0
25.0
>>>

If we mess something up, the interpreter also gives us detailed errors as shown below:

>>> import math
>>> for number in numbers:
...     print(math.pow(number*2))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: pow() takes exactly 2 arguments (1 given)

Summary

The article focuses on getting us familiar and comfortable with the Python interpreter, whether it's about getting some help or quickly testing a piece of code. Undoubtedly the interpreter is where most beginners start to learn Python, and the more we use it the more comfortable and efficient we get with it. In the next article, we will be talking about pip and some of its most useful commands.

Python (language) Object (computer science) Attribute (computing)

Published at DZone with permission of Gaurav Gahlot, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • What Java Version Are You Running? Let’s Take a Look Under the Hood of the JDK!
  • Simulate Network Latency and Packet Drop In Linux
  • Spring Cloud: How To Deal With Microservice Configuration (Part 1)
  • Unleashing the Power of JavaScript Modules: A Beginner’s Guide

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: