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.

iPython shell

Jupyter Notebook

The Jupyter notebook is a web-browser based graphical environment consisting of cells, which can consist of code, or text. The text cells should contain text in markdown syntax, which allows you to type not just words in bold and italic, but also tables, mathematical formula using latex, etc. The code cells of Jupyter can contain code in various languages, but here we will exclusively focus on code cells with Python 3.

For example, this block of text that begins with this sentence marks the beginning of a jupyter notebook cell containing markdown content. If you are viewing this from jupyter, click on jupyter's top menu -> Cell -> Cell Type to see what is the type of the current cell, or to change the cell type. Computations must be done in a code cell, not a markdown cell. For example, to compute $$ \cos(\pi \sqrt{\pi})^7 $$ we open a code cell next with the following two lines of python code:

In [1]:
from math import cos, sqrt, pi

cos(pi*sqrt(pi))**7
Out[1]:
0.14008146171564725

This seamless integration of text and code makes Jupyter attractive for developing a reproducible environment for scientific computing.

Python file

Open your favorite text editor, type in some python code, and then save the file as myfirstpy.py. Here is a simple example of such a file.

#------- myfirstpy.py ---------------------------------
from math import cos, sqrt, pi

print('Hello, I can compute! ')
x = 3
y = cos(pi*sqrt(pi)*x)**7
print('Starting from x =', x, 'we have computed y=', y)
#------------------------------------------------------

One executes such a python file by typing the following on the command line

python3 ../pyfiles/myfirstpy.py

Note that depending on your operating system, you may have to replace the above command by python ..\pyfiles\myfirstpy.py or similar variants.

You can also execute the python file in a platform-independent way from within this Jupyter notebook by loading the contents of the file into a cell. This is done using line magic command %load ../pyfiles/myfirstpy.py. Once you type in this command into a code cell and execute the cell, the contents of the file will be copied into the cell (and simultaneously, the load command will be commented out). Then, returning to the cell and executing the cell a second time runs the same code that was in the file.

In [2]:
# %load ../pyfiles/myfirstpy.py
from math import cos, sqrt, pi

print('Hello, I can compute! ')
x = 3
y = cos(pi*sqrt(pi)*x)**7
print('Starting from x =', x, 'we have computed y=', y)
Hello, I can compute! 
Starting from x = 3 we have computed y= -0.013884089495354414

The above output cell should display the same output as what one would have obtained if we executed the python file on the command line.

For larger projects (including take-home assignments), you will need to create such python files with many lines of python code. Therefore it is essential that you know how to create and execute python files in your system.