Python code and Jupyter notebooks#
Python code can be written and executed in different ways. We’ll first have a look at how to execute Python code from prepared files, which is commonly used to run software written in Python. Then, we’ll explain the usage of Jupyter notebooks, which allows the interactive execution of Python code in a browser-based environment, mostly used for scripting and data analysis with Python.
Python execution via Python files#
Python code can be written in “.py” files, which can be executed from the command line via the installed Python instance. We can do this with the simple file hello.py
in this folder.
Either, execute it in the terminal via python hello.py
.
Or, execute the following cell by selecting it and hitting Ctrl + Enter
Both will tell the Python interpreter to execute the code in the file.
!python hello.py
hello world
How a Jupyter notebook differs from Python files#
Running Python code in a Jupyter Notebook is different from running a file in the terminal. In a terminal, you execute the whole file at once. In a Jupyter Notebook, you can execute code in smaller pieces called ‘cells’.
How a Jupyter notebook works and its cell types#
A Jupyter Notebook is a web-based interactive computing platform. It allows you to create and share documents that contain code, equations, visualizations, and narrative text for documentation. There are three main types of cells in a Jupyter notebook:
Code Cells: These cells contain code you want to run. When executed, they display the output directly below the cell.
Markdown Cells: These cells contain text formatted using Markdown. Markdown is a simple way to format text using plain text symbols.
Raw Cells: These cells contain raw text that is not meant to be executed. They are useful for writing plain text or including results from other programs.
Keyboard shortcuts#
When working with Jupyter notebooks,
CTRL-ENTER
orSHIFT-ENTER
are the shortcuts people use all the time.If you want to “leave” a cell without executing it, you can also hit
ESCAPE
.You can add a new cell above the current cell by hitting
A
and below by hittingB
.You can delete cells by hitting
D
twice.
There are more shortcuts. You can see them all in the menu above Help > Keyboard shortcuts
or by hitting H
.
Try it out!
Markdown documentation in Jupyter notebooks#
Markdown is a markup language for describing the formating of text. To see the Markdown code which describes this text, double-click this cell in your Jupyter notebook. Hit CTRL+ENTER
to execute it and return to the viewing mode.
Bullet point
More bullet points
Deeper bullet points
List entry
Another list entry
More list entries
Let’s try executing some code in a code cell. Add a cell below to execute Python code which will print your name.