1  Introduction

Python is a high-level programming language that is widely used for web development, scientific computing, data analysis, artificial intelligence, and many other applications. Python was created in the late 1980s by Guido van Rossum, a Dutch programmer. It was originally designed as a hobby language to be easy to learn and read, but it quickly gained popularity among programmers for its simplicity and versatility. Python is a high-level, interpreted programming language.

Note

Contrary to what the name suggests, Python was not named after the snake. It was actually named after the comedy troupe Monty Python.

Show the code
import matplotlib.pyplot as plt

# Data for plotting
years = [1991, 1994, 2000, 2008, 2020, 2024]
python_events = [
    "Python released by Guido van Rossum",
    "Python 1.0: lambda, map, filter, reduce",
    "Python 2.0: list comprehensions, garbage collector",
    "Python 3.0: non-backwards compatible, community split",
    "Python 3.9: improved dictionary, IANA time zones",
    "Python 3.12: new features, optimizations"
]

world_events = [
    "Collapse of Soviet Union, Gulf War",
    "Rwandan Genocide, North Korean Nuclear Crisis",
    "Y2K Bug, Dot-com Bubble Burst",
    "Global Financial Crisis",
    "COVID-19 Pandemic",
    "Global Inflation Crisis"
]

# Create the plot
fig, ax = plt.subplots(figsize=(11, 5))

# Plot the events
ax.plot([1] * len(years), years, 'black', marker='o', markersize=6,zorder=3)
ax.set_xlim(0.5, 1.5)

# Annotate events
for i, (year, p_event, w_event) in enumerate(zip(years, python_events, world_events)):
    ax.text(1.02, year, f"{p_event}", ha='left', va='center', fontsize=10, wrap=True, color='black')
    ax.text(0.98, year, f"{year}: {w_event}", ha='right', va='center', fontsize=10, wrap=True, color='gray')

# Title and labels
ax.set_ylabel('Year', fontsize=12)
ax.set_xticks([])

# Show grid for better readability, with zorder to ensure they are beneath the text
#ax.grid(axis='y', zorder=1)

# Display the plot
plt.show()
A brief history of Python

A brief history of Python

A Brief History of Python:

  1. 1991: Python was first released by Guido van Rossum, who was then working at the Centrum Wiskunde & Informatica (CWI) in the Netherlands.
  2. 1994: Python 1.0 was released, which included features like lambda, map, filter, and reduce.
  3. 2000: Python 2.0 was released, which included major improvements like list comprehensions and a garbage collector.
  4. 2008: Python 3.0 was released, which included many changes that were not backwards-compatible with Python 2.x. This led to a split in the Python community, with some developers sticking with Python 2.x and others moving to Python 3.x.
  5. 2020: Python 3.9 was released, which included new features like improved dictionary performance and support for IANA time zones.
  6. Python 3.12.0 is the newest major release of the Python programming language, and it contains many new features and optimizations.

Today, Python is one of the most popular programming languages in the world. It is used by millions of developers and has a vast ecosystem of libraries and tools. Python is widely used for web development, scientific computing, data analysis, machine learning, and artificial intelligence. Python has a simple and readable syntax, which makes it easy to learn and use. It also has a large and active community of developers who contribute to the language and its ecosystem. Python has several popular implementations, including CPython, Jython, IronPython, and PyPy. CPython is the most widely used implementation and is the reference implementation of the language.

Python is expected to continue to grow in popularity in the coming years. Its simplicity and versatility make it well-suited for many applications, and its large ecosystem of libraries and tools makes it easy to develop complex applications quickly. Python is also widely used in the fields of data science and artificial intelligence, which are expected to continue to grow in importance in the coming years.

1.1 Programming

Before we dive into Python specifically, let’s first discuss how programs work in general.

  • A program is simply a set of instructions that a computer can follow to perform a specific task.
  • These instructions are written in a programming language, such as Python.

Programming languages can be classified into two categories:

  • high-level languages and low-level languages.
  • High-level languages are designed to be easier for humans to read and write, while low-level languages are closer to the machine language that a computer understands.

Python is a high-level language, which means that it is more abstract than low-level languages such as assembly or machine code. This abstraction makes it easier to write and read Python code, but it also means that Python programs may run slower than programs written in lower-level languages.

Python programs are typically executed using an interpreter. An interpreter is a program that reads and executes code written in a particular programming language. The Python interpreter is installed on most modern computers, so you don’t need to install anything special to run Python code.

When you write a Python program, you save it in a text file with a .py extension. This file contains the code that the Python interpreter will execute. To run the program, you simply type python followed by the name of the file in the command line.

Python code can also be compiled into a binary executable file, which can be run directly without the need for an interpreter. However, this is less common than using the interpreter, especially for small programs.

1.2 Jupyter Notebook

Jupyter Notebook is an interactive computing environment that allows you to create and share documents that contain live code, equations, visualizations, and narrative text. It is widely used for data science, machine learning, and scientific computing because of its ability to combine code, text, and visualizations in one place.

In Jupyter Notebook, code is executed in a separate process called a kernel. When you run a code cell, the code is sent to the kernel for execution. The kernel runs the code and sends the output back to the Notebook interface, where it is displayed. The kernel can be connected to different programming languages such as Python, R, Julia, and many more.

Jupyter Notebook Interface

Jupyter Notebook Interface

When you open a Jupyter Notebook, you are actually launching a web application that communicates with the kernel running in the background. The Notebook interface provides a web-based environment where you can create and edit notebooks, run code, and visualize the output.

One of the main advantages of using Jupyter Notebook is that you can edit and run code in small chunks, called cells. This allows you to test and debug your code incrementally, which can save you a lot of time and effort in the long run. You can also add narrative text, equations, and visualizations to your notebook to help explain your thought process and results.

Jupyter Notebook supports a wide variety of programming languages, and you can switch between them by selecting the appropriate kernel for your notebook. Each kernel has its own set of commands and syntax, but the overall Notebook interface remains the same.

1.3 Kernel vs Interpreter

An interpreter and a kernel are two different components of a programming environment, and they serve different purposes.

An interpreter is a program that reads and executes code written in a particular programming language. It takes source code as input and runs it directly, interpreting each line of code as it encounters it. Interpreters are commonly used in scripting languages like Python, Perl, and Ruby, where code is typically executed line-by-line rather than compiled into a binary executable. When you run a Python program using an interpreter, the interpreter reads the source code and executes it directly, without the need for compilation. On the other hand, a kernel is a program that provides an execution environment for a particular programming language. It communicates with the application or interface that hosts it and manages the execution of code within that environment. In the context of Jupyter Notebook, a kernel is a separate process that runs the code you write in a notebook cell. When you run a cell in Jupyter Notebook, the code in the cell is sent to the kernel for execution, and the results are returned to the notebook interface.

flowchart LR
      A1[Start: User Input] --> B1[Kernel Receives Input]
      B1 --> C1[Kernel Parses Input]
      C1 --> D1[Kernel Executes Code]
      D1 --> E1[Kernel Sends Output]
      E1 --> F1[Display Output to User]

So, while both an interpreter and a kernel are involved in the execution of code, they operate at different levels of abstraction. An interpreter is responsible for executing code line-by-line, while a kernel provides a runtime environment for executing code within an application or interface. Interpreters are typically used with scripting languages, while kernels are commonly used with interactive computing environments like Jupyter Notebook.

flowchart LR
      A2[Start: User Input] --> B2[Interpreter Receives Input]
      B2 --> C2[Interpreter Parses Input]
      C2 --> D2[Interpreter Executes Code]
      D2 --> E2[Display Output to User]

In the context of computing, a kernel is a program or a part of an operating system that serves as a bridge between software and hardware. It provides an abstraction layer that allows software to interact with hardware without having to worry about the specifics of the underlying hardware.

In the context of Jupyter Notebook, a kernel is a program that provides an execution environment for a particular programming language. It is responsible for interpreting and executing code written in that language, managing variables and memory, and returning results to the notebook interface. Each kernel runs in a separate process, isolated from the rest of the system, which makes it more secure and stable.

An execution environment is a runtime environment in which code is executed. It includes all the resources needed for the code to run, such as memory, processor time, and input/output devices. The execution environment manages the allocation of these resources to the code as it runs, ensuring that it has everything it needs to complete its task.

In the context of Jupyter Notebook, the kernel provides the execution environment for the code you write in a notebook cell. When you run a cell, the code is sent to the kernel for execution, and the kernel manages the resources needed to execute the code. It keeps track of variables and their values, manages memory, and ensures that the code has access to any necessary libraries or modules.

1.4 Anatomy of a Python Program

Let us look at a fully functional Python program. Here’s a Python code that generates a contour plot using the libraries (in python called packages) Matplotlib and NumPy: This code generates a contour plot of the function \(\sin(x^2 + y^2)\) with 20 contour levels and uses the ‘viridis’ colormap, which is aesthetically pleasing and perceptually uniform. The plot includes axis labels and a title for better understanding.

Show the code
import numpy as np
import matplotlib.pyplot as plt

# Create a grid of points
x = np.linspace(-3, 3, 400)
y = np.linspace(-3, 3, 400)
X, Y = np.meshgrid(x, y)

# Define a function for the contour plot
Z = np.sin(X**2 + Y**2)

# Create the figure
plt.figure(figsize=(8, 6))

# Display the image with a continuous color representation
im = plt.imshow(Z, extent=[-3, 3, -3, 3], origin='lower', cmap='Spectral', alpha=0.8)

# Create the contour plot
contour = plt.contour(X, Y, Z, levels=10, cmap='Spectral')

# Add a colorbar for reference
cbar = plt.colorbar(im, label='Z values')

# Set labels and title
plt.xlabel('X-axis')
plt.ylabel('Y-axis')

# Show the plot
plt.show()
Sin plot in polar coordinates

Sin plot in polar coordinates

  1. Import Necessary Libraries:

    import numpy as np
    import matplotlib.pyplot as plt
    • numpy is a library used for numerical operations in Python, especially with arrays and matrices.
    • matplotlib.pyplot is a plotting library used for creating static, interactive, and animated visualizations in Python.
  2. Create a Grid of Points:

    x = np.linspace(-3, 3, 400)
    y = np.linspace(-3, 3, 400)
    X, Y = np.meshgrid(x, y)
    • np.linspace(-3, 3, 400) generates 400 evenly spaced points between -3 and 3. This is done for both x and y to cover a range of values.
    • np.meshgrid(x, y) creates a grid of coordinates based on the x and y arrays. X and Y are matrices containing the x and y coordinates of each point in the grid, respectively.
  3. Define a Function for the Contour Plot:

    Z = np.sin(X**2 + Y**2)
    • This defines a function \(Z = \sin(X^2 + Y^2)\), which will be used to generate the contour plot. ** denotes exponentiation in Python.
  4. Create the Contour Plot:

    plt.figure(figsize=(8, 6))
    contour = plt.contour(X, Y, Z, levels=20, cmap='Spectral')
    • plt.figure(figsize=(8, 6)) creates a new figure for plotting with a specified size (8 inches by 6 inches).
    • plt.contour(X, Y, Z, levels=20, cmap='viridis') creates a contour plot using the X, Y, and Z matrices. levels=20 specifies that the plot should have 20 contour levels. cmap='viridis' specifies the colormap to use, which determines the colors of the contours.
  5. Add a Colorbar for Reference:

    plt.colorbar(contour)
    • plt.colorbar(contour) adds a colorbar to the plot, which provides a reference for the contour levels and their corresponding colors.
  6. Set Labels and Title:

    plt.xlabel('X-axis')
    plt.ylabel('Y-axis')
    • plt.xlabel('X-axis') and plt.ylabel('Y-axis') set the labels for the x and y axes.
    • plt.title('Aesthetically Pleasing Contour Plot') sets the title of the plot.
  7. Show the Plot:

    plt.show()
    • plt.show() displays the plot on the screen.

1.5 Coding Conventions

There are several coding conventions that are widely followed when programming in Python. The most important of these is the Python Enhancement Proposal (PEP) 8, which provides a set of guidelines for writing Python code that is easy to read, maintain, and understand. Here are some of the key coding conventions to keep in mind when programming in Python:

Important Conventions
  1. Use four spaces to indent code blocks. Do not use tabs.

  2. Use lowercase letters and underscores to name variables, functions, and modules.

  3. Use single quotes to enclose string literals, except when a string contains a single quote.

  4. Use descriptive and meaningful names for variables, functions, and classes.

  5. Avoid using single-character variable names, except for variables that represent mathematical values.

  6. Write comments to explain your code and make it more readable.

  7. Use whitespace to make your code more readable. For example, put spaces around operators and after commas in function arguments.

  8. Follow the PEP 8 style guide for the layout and formatting of your code.

  9. Use consistent naming conventions for classes, with each word capitalized, and no underscores.

  10. Always use parentheses to indicate the order of operations in expressions, even when they are not strictly necessary.

These are just a few of the coding conventions that are typically followed when programming in Python. Adhering to these conventions will help make your code more readable, easier to maintain, and more consistent with the wider Python community.

Four spaces are preferred over tabs in Python because Python relies on indentation to define code blocks, such as loops, functions, and conditional statements. Consistency in indentation is crucial in Python code to make it more readable and easier to understand. The problem with using tabs for indentation is that the actual width of a tab can vary between different text editors and environments. In some cases, a tab might take up four spaces, while in others, it might take up eight spaces or more. This can lead to inconsistencies in the way code is indented, making it harder to read and understand. On the other hand, using four spaces ensures a consistent and predictable indentation size, regardless of the text editor or environment being used. This makes the code more readable and easier to maintain, especially when different programmers are working on the same codebase.

1.6 Further Reading

  1. https://www.python.org
  2. https://peps.python.org/pep-0020/