How to Run Python Code

  • Python is a flexible language, and there are many ways to use. There are often more ways that just the one!
  • One thing that distinguishes Python from other programming languages is that it is interpreted rather than compiled. This means that the user has more freedom and allows the code to be more dynamic, though the disadvantage is that it is slightly slower.
  • The freedom allows programming to be interactive in a way that is not directly possible with compiled languages like Fortran, C, or Java.

There are four primary ways you can run Python code:

  • the Python interpreter
  • the IPython interpreter
  • via self-contained scripts
  • Jupyter Notebook.

The most basic way: Python Interpreter

The Python interpreter can be started by installing the Python language and typing python at the command prompt. On Windows Python interpreter can be invoked from the Command Prompt application or from the Start menu.

Python 3.5.2 | packaged by conda-forge | (default, Jul 26 2016, 01:32:08) 
[GCC 4.8.2 20140120 (Red Hat 4.8.2-15)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

With the interpreter running, you can begin to type and execute code snippets. Here we'll use the interpreter as a simple calculator, performing calculations and assigning values to variables:

>>> 1 + 1
2
>>> x = 5
>>> x * 3
15

The interpreter makes it very convenient to try out small snippets of Python code and to experiment with short sequences of operations.

More convenient way: the IPython interpreter

  • If you spend much time with the basic Python interpreter, you'll find that it lacks many of the features of a full-fledged interactive development environment.

An alternative interpreter called IPython (for Interactive Python) includes a host of convenient enhancements to the basic Python interpreter.

It can be started by typing ipython at the command prompt (or from Start menu on Windows):

$ ipython
Python 3.5.2 | packaged by conda-forge | (default, Jul 26 2016, 01:32:08) 
Type "copyright", "credits" or "license" for more information.

IPython 5.1.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.
ipython
In [1]:

The main aesthetic difference between the Python interpreter and the enhanced IPython interpreter lies in the command prompt: Python uses >>> by default, while IPython uses numbered commands (e.g. In [1]:).

Regardless, we can execute code line by line just as we did before:

ipython
In [1]: 1 + 1
Out[1]: 2

In [2]: x = 5

In [3]: x * 3
Out[3]: 15

Note that just as the input is numbered, the output of each command is numbered as well.

Some useful IPython commands and magic functions

Command Description
foo? get help for the object 'foo'
foo?? get more help for the object 'foo'
%hist Command history. %hist -g foo will search history for 'foo'
_i, _ii, _iii Previous, next previous, next next previous input
_, __, ___ Previous, next previous, next next previous output
%timeit x=2**100 time the execution of x=2**100
%reset Cleans up the namespace
%lsmagic print currently available magic functions
Cell magic Description
%%timeit x=20
x**100
time x**100 with a setup of x=20; setup code is not counted
%%writefile blahblah.txt
text inside some file
write text to file

An extended IPython reference card is available here.

Self-contained Python scripts

Running Python snippets line by line is useful in some cases, but for more complicated programs it is more convenient to save code to file, and execute it all at once.

By convention, Python scripts are saved in files with a .py extension. For example, let's create a script called test.py which contains the following:

# file: test.py
print("Running test.py")
x = 5
print("Result is", 3 * x)

To run this file, we make sure it is in the current directory and type python filename at the command prompt:

$ python test.py
Running test.py
Result is 15

For more complicated programs, creating self-contained scripts like this one is a must.

Aside: what are *.pyc files?

CPython compiles its source code into "byte code", and for performance reasons, it caches this byte code on the file system whenever the source file has changes. This makes loading of Python modules much faster because the compilation phase can be bypassed. When your source file is foo.py , CPython caches the byte code in a foo.pyc file right next to the source.

The Jupyter notebook

A useful hybrid of the interactive terminal and the self-contained script is the Jupyter notebook, a document format that allows executable code, formatted text, graphics, and even interactive features to be combined into a single document.

Though the notebook began as a Python-only format, it has since been made compatible with a large number of programming languages, and is now an essential part of the Jupyter Project.

The notebook is useful both as a development environment, and as a means of sharing work via rich computational and data-driven narratives that mix together code, figures, data, and text.

That's what we are using today to give you this presentation and will be using later throughout the workshop.

References

A Whirlwind Tour of Python by Jake VanderPlas (O’Reilly). Copyright 2016 O’Reilly Media, Inc., 978-1-491-96465-1