{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Basic elements of Python\n", "This lesson aims to provide an overview of some of the basic elements in the Python programming language. In the first section these include how to define and use variables, the concept of a data type and how to determine the data type of a variable in Python, and Python lists. Later parts of the lesson introduce the [NumPy numerical Python library](http://www.numpy.org/), and the main conceptual programming components we will use: functions, loops, and conditional statements.\n", "\n", "Please note that this is not intended to be a comprehensive introduction, but rather something to give you enough background to be able to work on the programming assignments later in this course. For more about basic Python programming we refer you to the [Geo-Python course lessons](https://geo-python.github.io), [Codecademy](https://www.codecademy.com/learn/python), and the [Interactive Python Tutorial](https://www.learnpython.org/).\n", "\n", "### Sources\n", "This lesson is inspired by the [Programming in Python lessons](http://swcarpentry.github.io/python-novice-inflammation/) from the [Software Carpentry organization](http://software-carpentry.org).\n", "\n", "### About this document\n", "This is a Jupyter Notebook designed to assess your understanding of the basic concepts of programming in Python. The contents of this document are divided into cells, which can contain Markdown-formatted text, Python code, or raw text. You can execute a snippet of code in a cell by pressing **Shift-Enter**. Try this out in the examples below." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Getting started\n", "Presumably if you have made it this far, you have already opened this Jupyter Notebook on your own computer. If not, you can do the following to launch [Jupyter Lab](http://jupyterlab.readthedocs.io/en/stable/) by typing the following in a terminal window." ] }, { "cell_type": "raw", "metadata": {}, "source": [ "$ jupyter lab" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This should open a new Jupyter Lab session from which you can open this document by navigating its location in the **Files** tab and double clicking on it. After that you should be ready to go." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables, math and functions\n", "\n", "We will start our Python lesson by learning a bit of the basic operations you can perform using Python.\n", "\n", "### Simple Python math\n", "\n", "Python can be used as a simple calculator. Remember, you can press **Shift-Enter** to execute the code in the cells below. Try it out by typing `1 + 1` or `5 * 7` and see what you get." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Add 1 + 1\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Multiply 5 * 7\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you want to edit and re-run some code, simply make changes to the cell and press **Shift-Enter** to execute the revised code." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Math operations\n", "\n", "The list of basic arithmetic operations that can be done by default in Python is in the table below.\n", "\n", "| Operation | Symbol | Example syntax | Returned value |\n", "| -------------- | ------ | -------------- | -------------- |\n", "| Addition | `+` | `2 + 2` | `4` |\n", "| Subtraction | `-` | `4 - 2` | `2` |\n", "| Multiplication | `*` | `2 * 3` | `6` | \n", "| Division | `/` | `4 / 2` | `2` |\n", "| Exponentiation | `**` | `2**3` | `8` |\n", "\n", "For anything more advanced, we need to load a *module*. For math operations, this module is called *math* and it can be loaded by typing `import math`. Try that below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Import math below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have access to functions in the math module, we can use it by typing the module name, a period (dot), and the the name of the function we want to use. For example, `math.sin(3)` or `math.sqrt(4)`. Try these examples out below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculate the sine of 3 below\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Calculate the square root of 4 below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s summarize what we’ve just seen with modules:\n", "\n", "1. A *module* is a group of code items such as functions that are related to one another. Individual modules are often in a group referred to as a *library*.\n", "2. Modules can be loaded using `import`. Functions that are part of the module `modulename` can then be used by typing `modulename.functionname()`. For example, `sin()` is a function that is part of the `math` module, and used by typing `math.sin()` with some number between the parentheses.\n", "3. Within a given Jupyter Notebook the variables you define earlier in the notebook will be available for use in the cells that follow as long as you have already executed the cells.\n", "4. Modules may also contain constants such as `math.pi`. Type this in the cell below to see the value of the contant `math.pi`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check the value of math.pi below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Combining functions\n", "\n", "Functions can also be combined. The `print()` function returns values within the parentheses as text on the screen. Below, try printing the value of the square root of four." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the square root of four below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can also combine text with other calculated values using the `print()` function. For example, `print('Two plus two is', 2+2)` would generate text reading 'Two plus two is 4'. Combine the `print()` function with the `math.sqrt()` function in the cell below to produce text that reads 'The square root of 4 is 2.0'." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the \"fancy\" text below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variables\n", "\n", "*Variables* can be used to store values calculated in expressions and used for other calculations. Assigning value to variables is straightforward. To assign a value, you simply type `variable_name = value`, where `variable_name` is the name of the variable you wish to define. In the cell below, define a variable called `temp_celsius`, assign it a value of '10.0', and then print that variable value using the `print()` function. Note that you need to do this on two separate lines." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define and print temp_celsius below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we did above, you can combine text and even use some math when printing out variable values. The idea is similar to the examples of adding 2+2 or calculating the square root of four from the previous section. In the cell below, print out the value of `temp_celsius` in degrees Fahrenheit by multiplying `temp_celsius` by 9/5 and adding 32. This should be done within the `print()` function to produce output that reads 'Temperature in Fahrenheit: 50.0'." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the temperature of temp_celsius in Fahrenheit\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that if you try to run some code that accesses a variable that has not yet been defined you will get a `NameError` message." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [ "raises-exception" ] }, "outputs": [], "source": [ "print('Temperature in Celsius:', 5/9 * (tempFahrenheit - 32))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "One of the cool things here is that if we define the undefined variable in a later cell and execute that cell, we can return to the earlier one and the code should now work. That was a bit of a complicated sentence, so let's test this all out. First, assign a value to the variable `tempFahrenheit` in the cell below. Then, return to the cell above this text and run it again. See how the error message has gone away? `tempFahrenheit` has now been defined and thus the cell above no longer generates a `NameError` when the code is executed.\n", "\n", "Note that the number beside the cell, for example `In [2]`, tells you the order in which the Python cells have been executed. This way you can see a history of the commands you've executed." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define tempFahrenheit below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Data types\n", "\n", "There are 4 basic *data types* in Python as shown in the table below.\n", "\n", "| Data type name | Data type | Example |\n", "| -------------- | -------------------- | ---------- |\n", "| `int` | Whole integer values | `4` |\n", "| `float` | Decimal values | `3.1415` |\n", "| `str` | Character strings | `'Hot'` |\n", "| `bool` | True/false values | `True` |\n", " \n", "The data type can be found using the `type()` function.\n", "As you will see, the data types are important because some are not compatible with one another.\n", "\n", "Let’s define a variable `weatherForecast` and assign it the value 'Hot'. After this, we can check its data type using the `type()` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Define weatherForecast and check its type below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let’s also check the type of `tempFahrenheit`. What happens if you try to combine `tempFahrenheit` and `weatherForecast` in a single math equation such as `tempFahrenheit = tempFahrenheit + 5.0 * weatherForecast`?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Combine tempFahrenheit and weatherForecast below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this case we get at `TypeError` because we are trying to execute a math operation with data types that are not compatible. There is no way in Python to multpily numbers with a character string." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Lists and indices\n", "\n", "Let's now consider an example of some rock samples collected during a recent field excursion. Rather than having individual variables for each of the samples, we can store many related values in a *collection*. The simplest type of collection in Python is a **list**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Creating a list\n", "\n", "Let's first create a list called `sampleIDs` and print it to the screen." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sampleIDs = ['DW-NP-03', 'DW-NP-12', 'DW-NP-33', 'DW-NP-48']\n", "print(sampleIDs)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also check the type of the `sampleIDs` list using the `type()` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Check the type of sampleIDs below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we have a list of 4 sampleID values in a list called sampleIDs.\n", "As you can see, the `type()` function recognizes this as a list.\n", "Lists can be created using the square brackets (`[` and `]`), with commas separating the values in the list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Index values\n", "\n", "To access an individual value in the list we need to use an *index value*.\n", "An index value is a number that refers to a given position in the list.\n", "Let's check out the first value in our list as an example by printing out `sampleIDs[1]`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the first value of sampleIDs below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that Python (and many other programming languages) start values stored in collections with the index value `0`. Print out the actual first value of the list `sampleIDs` in the cell below." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Print the actual first value of sampleIDs below\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Length of a list\n", "\n", "We can find the length of a list using the `len()` function. Use it in the cell below to find the length of the list `sampleIDs`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Use the len function to check the length of sampleIDs\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Just as expected, there are 4 values in our list and `len(sampleIDs)` returns a value of `4`." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise - Getting to know lists\n", "\n", "- Create a Python list containing 4 items/values and store it with the variable `my_list`.\n", "- After you have created the list, check its data type, then use the index values to check the data types of the contents of the list.\n", "- What kinds of data can you store in lists? Does each list value need to be the same data type?" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# You can create your example list in this cell\n", "# By the way, you can comment lines in Python (or a Jupyter Notebook Python cell)\n", "# by starting the line with a number sign\n", "# Comments are not executed, but can help explain what you code does\n", "\n", "# Put your code below\n" ] } ], "metadata": { "celltoolbar": "Tags", "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.2" } }, "nbformat": 4, "nbformat_minor": 2 }