{ "cells": [ { "cell_type": "markdown", "id": "8f6bbaa9", "metadata": {}, "source": [ "# About Python\n", "\n", "```{admonition} Interactive page\n", ":class: warning, dropdown\n", "This is an interactive book page. To solve quizzes and run Python code cells, press launch button at the top right side of the page (look for a small rocket icon) and then *Live Code*.\n", "```\n", "\n", "## Interacting with Python\n", "\n", "There are various ways in which you can interact with Python language and run Python code:\n", "- **Terminal**. You can create and edit Python scripts using a text editor such as Notepad or Vim (because Python scripts are text files), and then run them from the terminal.\n", "- **IDE**. IDEs are comprehensive development environments which you can use to write, test, and debug your code. They can also be linked to Git for version control and offer a set of useful features that can help you with programming. We recommend using IDE called Visual Studio Code (VS Code) alongside this book's materials.\n", "- **This book**. In this book, we offer interactive pages which, once launched, contain interactive Python coding cells. This page is also an interactive page. You can use in-book Python coding cells while learning and exploring new concepts. However, when working on larger pieces of code, such as exercises from this book, you are encouraged to do it in IDE.\n", "- **Jupyter notebooks**. Notebooks are another popular way to interact with Python. They provide an interactive programming environment, in which you can incorporate text and blocks/cells of code. If you're curious to learn more, take a look at this [quick start guide](https://jupyter-notebook-beginner-guide.readthedocs.io/en/latest/).\n", "\n", "```{figure} ../images/chapter3/VS-Code-interface.png\n", "---\n", "height: 450px\n", "name: VSCode-interface\n", "---\n", "VS Code interface. We will install VS Code and walk you through its usage in the subsequent pages. You can also visit [VS Code website](https://code.visualstudio.com/docs/getstarted/userinterface) to learn more.\n", "\n", "```{figure} ../images/chapter3/jupyter-notebook-interface.png\n", "---\n", "height: 400px\n", "name: ipynb-interface\n", "---\n", "Jupyter notebook interface. To learn more, visit [Jupyter notebook website](https://jupyter-notebook.readthedocs.io/en/latest/).\n" ] }, { "cell_type": "markdown", "id": "8b6628c8", "metadata": {}, "source": [ "## An interpreted language\n", "\n", "**Python is an interpreted computer programming language.** \n", "Every time you run Python (either in the command line, in an IDE such as VS Code, or in a Jupyter notebook), a Python **kernel** is created. \n", "This kernel is a copy of the Python program (*interpreter*) that runs on your computer.\n", "You can interact with and give commands to the kernel by typing Python commands in VS Code (or a code cell in a Jupyter notebook).\n", "\n", "Interactive code cells are also included in this book, allowing you to **run Python code from within this book**.\n", "For example, the cell below contains Python code that prints the text `Hello world!` (a classical way to start learning programming).\n", "To run this Python code cell, press `run`. \n", "Remember that you have to launch a live version of the page to run Python code. \n", "\n", "What output do you get when you `run` this code?\n", "Can you make the code print out something else, such as your name?" ] }, { "cell_type": "code", "execution_count": null, "id": "ded25f8d", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "print(\"Hello world!\")" ] }, { "cell_type": "markdown", "id": "4ef14bf5", "metadata": {}, "source": [ "When you run the cell, the code will be sent to the Python kernel, which will translate your command into a binary language your computer CPU understands, send it to the CPU, and read back the answer. \n", "If the code you run produces an output, meaning that the kernel will send something back to you (in the above example, the printed text), then the output that your code produces will be displayed in the VS Code terminal (or below the code cell here in the book). \n", "\n", "```{figure} ../images/chapter3/kernel.png\n", "---\n", "height: 400px\n", "name: kernel\n", "---\n", "Scheme of what running a Python code looks like \"behind the scenes\".\n", "```" ] }, { "cell_type": "markdown", "id": "712ec5a3", "metadata": {}, "source": [ "Your code can of course contain multiple lines and commands.\n", "In addition, it is good practice to add **comments** to your code to explain what it's doing.\n", "This makes your code more readable both to yourself and others, and it's good practice to comment your code (see section on [good coding pratices](../chapter5/good-coding-practices.ipynb)).\n", "Starting a line with a hashtag `#` tells Python to ignore the line when executing code, so we use `#` for writing comments." ] }, { "cell_type": "code", "execution_count": null, "id": "c0962825", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "# This is a line of comments and it is not executed\n", "# Comments are amazing for explaining what the code does\n", "# The line below prints a message that greets the world\n", "print(\"Hello world!\")\n", "print(\"Goodbye\")" ] }, { "cell_type": "markdown", "id": "c6e8798e", "metadata": {}, "source": [ "```{admonition} Compiled and interpreted languages\n", ":class: note\n", "On the basis of how a programming language is processed, we make a distinction between compiled and interpreted languages.\n", "Python belongs to the latter group.\n", "\n", "**Compiled language** source code has to be compiled into machine code (binary language), which can then be executed by your computer's CPUs.\n", "IDEs have built-in compilers that can do this for you.\n", "While compiled language code is faster because it gets translated into machine code prior to execution, it is also less portable because it's optimized for specific hardware and OS on which it is meant to run.\n", "Examples of compiled languages include **C**, **C++**, and **Java**.\n", "\n", "For **intepreted languages**, the source code is read and executed line by line directly by an interpreter.\n", "In other words, the interpreter translates code into machine code at runtime, directly in an IDE or command line, and there is no separate compilation step.\n", "Translation at runtime makes interpreted languages slower, but also more portable.\n", "Examples of interpreted languages include **Python**, **JavaScript**, and **Ruby**.\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "baebf621", "metadata": { "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [] }, { "cell_type": "markdown", "id": "861c2a07", "metadata": {}, "source": [ "## Natural vs. programming language\n", "\n", "While Python may resemble plain English, there are still crucial **differences** between natural languages (such as English) and programming languages (such as Python).\n", "\n", "Programming languages have **very strict syntax** and there is **no tolerance for errors** - even a small syntax error may prevent your Python code from running and must be corrected. Note that this is analogous to other fields of science: \n", "\n", "| Field | Correct syntax | Incorrect syntax |\n", "| ----------- | -------------- | -----------------|\n", "| Mathematics | 3 + 3 = 6 | 3 = +6* |\n", "| Chemistry | H2O | 2XeMg |\n", "| Python | print(\"Hello world!\") | \"print(Hello world!\") |\n", "\n", "Let's see this in practice with `print()` that we used above. In Python, when we want to print some text, such as \"Hello world!\", the correct syntax is using the `print` statement with round brackets, and the text inside the brackets has to be in quotation marks.\n", "\n", "What happens if one or both quotations marks are missing or misplaced? What happens if you have a typo in `print`, e.g., `prit`?\n", "Use the code cell below to introduce mistakes into Python's `print` statement and try to run the code with mistakes." ] }, { "cell_type": "code", "execution_count": null, "id": "fbd035e2", "metadata": { "tags": [ "remove-output" ] }, "outputs": [], "source": [ "print(\"Hello world!\")" ] }, { "cell_type": "markdown", "id": "434fa593", "metadata": {}, "source": [ "## Python kernel has memory\n", "\n", "In addition to having Python do things for you, such as printing `Hello world!`, you can also make **Python kernel remember things** for you.\n", "Let's say you want Python to remember number 5 for you. \n", "You can execute the following line:" ] }, { "cell_type": "code", "execution_count": null, "id": "b38996cc", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "a = 5" ] }, { "cell_type": "markdown", "id": "494cdd4d", "metadata": {}, "source": [ "In Python, the `=` symbol represents the **assignment operator**: it is an instruction to assign the value of 5 to the **variable** called `a`. \n", "If `a` already exists, it will be over-written with the new value; if variable `a` does not yet exist, then Python will create a new variable for you automatically.\n", "Therefore, the cell above created variable `a` that has the value of 5 in the memory of the Python kernel. \n", "We can check that `a` is indeed remembered by now printing its value:\n" ] }, { "cell_type": "code", "execution_count": null, "id": "49049e34", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "print(a)" ] }, { "cell_type": "markdown", "id": "b86a8c22", "metadata": {}, "source": [ "\n", "```{warning}\n", "The equation sign can have **different meanings in Python**, depending on how you use it:\n", "- `=` is the **assignment operator**: it assigns values to variables. Running `a = 5` will assign 5 to `a`.\n", "- `==` is the **equality operator**: it compares operands for equality. If we have defined `a` to be 5, running `a == 5` will return a boolean `True`. We will learn more about the `==` operator in a later section on [Flow control](../chapter6/conditional-statements.ipynb).\n", "```" ] }, { "cell_type": "markdown", "id": "d294d8c7", "metadata": {}, "source": [ "Besides **numerical values**, variables can also be **strings**, which are sequences of characters. \n", "You make a string by putting the text between the quotation marks.\n", "Can you guess what the printed output of the following command will be?" ] }, { "cell_type": "code", "execution_count": null, "id": "9db6d34e", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "print(\"a\")" ] }, { "cell_type": "markdown", "id": "aa4bb01d", "metadata": {}, "source": [ "Note that we can also combine several variables, or strings and a variable, within one `print` statement using a comma `,`.\n", "This can be used to add a message, i.e., some context to the variables you're printing." ] }, { "cell_type": "code", "execution_count": null, "id": "b339594b", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "print(\"My favourite number is\", a)" ] }, { "cell_type": "markdown", "id": "6bd81a5a", "metadata": {}, "source": [ "```{exercise}\n", ":class: dropdown\n", "Write a Python code containing two lines. \n", "- In the first line, assign the numerical value 3.14 to a variable called `pi`. \n", "- In the second line, use a `print` statement to print out the value of your variable. Add a descriptive string in `print` (e.g., \"The approximate value of pi is\").\n", "- Can you also use special symbols in strings, e.g., if you were to write \"The approximate value of pi =\"?\n", "```" ] }, { "cell_type": "code", "execution_count": null, "id": "cca1c646", "metadata": { "tags": [ "remove-output" ], "vscode": { "languageId": "plaintext" } }, "outputs": [], "source": [ "# Use this cell to write your code " ] } ], "metadata": { "jupytext": { "cell_metadata_filter": "-all", "main_language": "python", "notebook_metadata_filter": "-all" }, "language_info": { "name": "python" } }, "nbformat": 4, "nbformat_minor": 5 }