Interacting with Python¶


March 31, 2020


Python is a modern, general-purpose, object-oriented, high-level programming language with a clean and expressive syntax. The following features make for easy code development and debugging in python:

  • Python code is interpreted: There is no need to compile the code. Your code is read by a python interpreter and made into executable instructions for your computer in real time.

  • Python is dynamically typed: There is no need to declare the type of a variable or the type of an input to a function.

  • Python has automatic garbage collection or memory management: There is no need to explicitly allocate memory for variables before you use them or deallocate them after use.

However, keep in mind that these features also make pure python code slower (than, say C) in repetitious loops because of repeated checking for the type of objects. Therefore many python modules (such as numpy, which we shall see in detail soon), have C or other compiled code, which is then wrapped in python to take advantage of python's usability without losing speed.

There are at least four ways to interact with your Python 3 installation.

  1. Use a python shell
  2. Use an iPython shell
  3. Put code in a python file ending in .py
  4. Write code + text in Jupyter notebook

Python shell¶

Type the python command you use in your system (python or python3) to get this shell. I will use python3 since that is what my system requires, but please do make sure to replace it by python if that's what is needed on your system. Here is an image of the interactive python shell within a terminal.

Python shell

Note the following from the interactive session displayed in the figure above:

  • Computing the square root of a number using sqrt is successful only after importing math. Most of the functionality in Python is provided by modules, like the math module. Some modules, like math, come with python, while others must be installed after python is installed.

  • Strings that begin with # (like "# works!" in the figure) differentiate comments from code. This is the case in a python shell and also in the other forms of interacting with python discussed below.

  • The dir command shows the facilities provided by a module. As you can see, the math module contains many functions in addition to sqrt.

iPython shell¶

A more powerful shell interactive environment is provided by the iPython shell (type in ipython or ipython3 into your command prompt, or launch it from Anaconda navigator). The iPython shell has features like auto-completion, coloring, history of commands, automatic help by tacking on ?, ability to interact with your operating system's commands, etc.