{ "cells": [ { "cell_type": "markdown", "id": "be328de7-72a2-46b0-87c0-967f373d00a1", "metadata": {}, "source": [ "# Hydrology and Hydrogeology\n", "## Programming with Python (1)\n", "#### (10 minutes)\n", "Here, you will learn the basics of programming with Python. \n", "There are \"markdown\" boxes (like this one) where you can learn about the assignment, and \"code\" boxes, that you can edit and run.\n", "\n", "\n", "Keep the following in mind:\n", "### (1) To move down or run the code, press Shift-Enter\n", "### (2) Each jupyter \"kernel\" only remains active for a few minutes when idle. If you are not finished, run something from time to time.\n", "### (3) Python is structured with \"identations\" or \"tabs\". If there are errors, pay atte\n", "ntion to it.\n", "### (4) The execution moves \"downward\" and has memory. If you \"jump\" block executions there may be errors. \n", "\n", "Good luck :)\n" ] }, { "cell_type": "markdown", "id": "dbc0b09b-4cc9-4830-9523-a608a371e38f", "metadata": {}, "source": [ "## Super basic code\n", "Because I lack imagination... the Hello world.\n", "\n", "`print(...)` is a function. \n", "**' '** or **\" \"** indicate what is inside is a string. \n", "**#** is one way of including comments in the code." ] }, { "cell_type": "code", "execution_count": null, "id": "39d21267-41a4-4267-8643-0d3182ed5af9", "metadata": {}, "outputs": [], "source": [ "# some comment\n", "\n", "print('Hello world') # comments may be here as well\n" ] }, { "cell_type": "markdown", "id": "84cff5e3-d490-4a51-a264-b8707a1acedc", "metadata": {}, "source": [ "## Variables\n", "Variabes are assigned with a **=** sign.\n", "The **list** (or **[]**) and the dictionary (or **{}**) are special types of variables in python.\n", "- They contain arbitrary things.\n", "- Both can be accessed with **[]**.\n", "- In the case of lists, with numbers from 0 to the length of the list -1.\n", "- In the case of dictionaries, with \"keys\".\n", "\n", "\n", "Play with the example below and try to understand the output prints...\n" ] }, { "cell_type": "code", "execution_count": null, "id": "3bc94fca-04d6-41e2-aaef-367ff3100fd0", "metadata": {}, "outputs": [], "source": [ "a = 1 \n", "print(a)\n", "\n", "variable_b = \"I am a long line of text\"\n", "print(variable_b)\n", "\n", "a = variable_b\n", "print(a)\n", "\n", "# Now a list\n", "some_list = [variable_b, 12, 'other string']\n", "print(some_list)\n", "\n", "print('The length of the list is:')\n", "print(len(some_list))\n", "\n", " # Add things to a list\n", "some_list.append(123)\n", "print(some_list)\n", "\n", "print('The length of the list is:')\n", "print(len(some_list))\n", "\n", " # Access things in a list\n", "c = some_list[0]\n", "print(c)\n", "\n", " # Modify things in a list\n", "some_list[1] = 'something new'\n", "print(some_list)\n", "\n", "# And a dictionary:\n", "some_dict = {}\n", "\n", "print('The length of the dictionary is:')\n", "print(len(some_dict))\n", "\n", " # Add things to a dictionary\n", "some_dict['a key'] = 54\n", "some_dict['another key'] = 'something else inside!'\n", "\n", "print(some_dict)\n", "\n", "print('The length of the dictionary is:')\n", "print(len(some_dict))\n", "\n", " # Access things in a dictionary\n", "print(some_dict['a key'])\n", "\n", " # Change things in a dictionary\n", "some_dict['another key'] = 'hello!'\n", "print(some_dict)\n", "\n" ] }, { "cell_type": "markdown", "id": "8894dbb3-8c6c-422b-a717-f6d36c829326", "metadata": {}, "source": [ "## Errors\n", "Sometimes things do not go as planned. Then you get errors. \n", "Below, we are trying to get information from a list that is too short! \n", "The type and message of the error provide useful information. \n", "For example: 'list index out of range'\n", "\n", "Experiment with the dictionary... Comment the first line below with **#** and search for a key that does not exist in \"some_dict\"\n" ] }, { "cell_type": "code", "execution_count": null, "id": "a375ef5f-b7c9-422e-b3ea-f15b2428f2bc", "metadata": {}, "outputs": [], "source": [ "some_list[23]\n", "\n", "#some_dict['not my key!']" ] }, { "cell_type": "markdown", "id": "cb6b0451-1d84-4e13-a948-938f7e33a79b", "metadata": {}, "source": [ "## Getting complicated with logic, operators, and loops\n", "Some examples of loops are:\n", "- `if` `elif` `else`\n", "- `for`\n", "- `while`\n", "\n", "The main operators are:\n", "- == (equal)\n", "- != (differnt)\n", "- \\>= and <= (greater than or equal / smaller than or equal)\n", "- and\n", "- or\n", "- not\n", "\n", "**True** and **False** may be used as \"boolean\" variables\n", "\n", "Pay attention to the **sintax** and **indentation**!" ] }, { "cell_type": "code", "execution_count": null, "id": "2aa20a73-c60b-4bc3-a468-aa95456e071a", "metadata": {}, "outputs": [], "source": [ "# The if elif else clause\n", " # Experiment with different values of z to get all 3 messages\n", "z = 2\n", "if z==2: # == is the \"equal\" operator\n", " print('z is 2')\n", "elif z>1000: # standing for else, if\n", " print('z is large!')\n", "else: # if all previous clauses fail...\n", " print('z is something else...')\n", "\n", "print('\\n')\n", "if z==2 and True:\n", " print('Yes!')\n", "else:\n", " print('No!')\n", "\n", "# The for clause (my favorite)\n", "# will loop through all items in a list\n", "print('\\n')\n", "another_list = [1, 2, 'abc', 122, 23, [0, 0, -1], 2]\n", "for i in another_list:\n", " print(i)\n", "\n", "print('\\n')\n", "for i in range(2, 20, 3): # range is a special operator. In this case, from 2 to 20-1 in steps of 3\n", " print(i)\n", "\n", "# The while clause\n", "print('\\n')\n", "counter = -2\n", "condition = True\n", "while condition:\n", " if counter!=3: # != is the \"different\" operator\n", " print(counter)\n", " counter = counter + 1 # or counter += 1\n", " else:\n", " condition=False # This will cause the loop to end" ] }, { "cell_type": "markdown", "id": "5cd855f2-2e33-433c-8186-ef3119e5d350", "metadata": {}, "source": [ "## Functions\n", "\n", "In Python, a **function** is a block of reusable code that performs a specific task. Functions help organize code, reduce repetition, and improve readability.\n", "\n", "A function is defined using the `def` keyword, followed by the function name and parentheses. You can pass parameters inside the parentheses, and the code block that makes up the function is **indented** (same as for the loops we have seen before). Optionally, a function can return a value using the `return` statement." ] }, { "cell_type": "code", "execution_count": null, "id": "b8a5783b-fb0a-4816-88fc-3aeada5b0621", "metadata": {}, "outputs": [], "source": [ "# Define a simple function that prints a greeting message.\n", "def greet(name):\n", " print(\"Hello, \" + name + \"!\")\n", "\n", "# Call the function with a sample name.\n", "greet(\"Alice\")" ] }, { "cell_type": "markdown", "id": "11d274a0-c92d-498f-b420-ef1afac4cc8d", "metadata": {}, "source": [ "## Functions that return values\n", "\n", "In addition to printing messages, functions can perform calculations and return results. Below is an example of a function that adds two numbers and returns their sum." ] }, { "cell_type": "code", "execution_count": null, "id": "ce054720-10b5-41d9-a493-a503272577ca", "metadata": { "scrolled": true }, "outputs": [], "source": [ "# Define a function that adds two numbers.\n", "def add(a, b):\n", " \"\"\"Returns the sum of a and b.\"\"\"\n", " return a + b\n", "\n", "# Call the function and store the result.\n", "result = add(5, 3)\n", "\n", "# Print the result.\n", "print(\"The sum of 5 and 3 is\", result)" ] }, { "cell_type": "markdown", "id": "14ff5ea1-fe92-4500-94ec-042444d303ee", "metadata": {}, "source": [ "## Classes\n", "\n", "In Python, a **class** is a blueprint for creating objects. Classes allow you to bundle data (attributes) and functionality (methods) together. Once defined, you can create multiple objects (instances) from a class.\n", "\n", "A class is defined using the `class` keyword. Typically, you'll define an `__init__` method to initialize new objects and other methods to define behaviors.\n", "\n", "You can add as many attributes and methods as you wish." ] }, { "cell_type": "code", "execution_count": null, "id": "67ceb899-e8b1-45e2-9acd-551936f7798b", "metadata": {}, "outputs": [], "source": [ "# Define a simple class called Person.\n", "class Person:\n", " def __init__(self, name, age):\n", " '''\n", " The __init__ method initializes a new Person object.\n", " - name: the name of the person\n", " - age: the age of the person\n", " '''\n", " self.name = name\n", " self.age = age\n", "\n", " def introduce(self):\n", " \"\"\"Prints an introduction message.\"\"\"\n", " print(f\"Hi, I'm {self.name} and I'm {self.age} years old.\")\n", "\n", "# Create an instance of the Person class.\n", "person1 = Person(\"Alice\", 30)\n", "\n", "# Call the introduce method on the person1 instance.\n", "person1.introduce()\n", "\n", "# Test it with another person...\n", "#you = Person(\"Your name\", 23)\n", "#you.introduce()\n" ] }, { "cell_type": "markdown", "id": "a21ad646-ab87-45a4-beea-1d101d067901", "metadata": {}, "source": [ "## Modules\n", "Finally, you can import modules for additional functionality. There are really a lot of them. Some examples are:\n", "- **pandas** (to handle data operations, for example .csv or .xlsx)\n", "- **numpy** (maths and matrix algebra)\n", "- **matplotlib** (for plots)\n", "- **sklearn** (for machine learning!)\n", "\n", "They can be imported in several ways. Check the examples below." ] }, { "cell_type": "code", "execution_count": null, "id": "dbf62269-176b-4f12-86f3-6f7cbf158ba7", "metadata": {}, "outputs": [], "source": [ "import math\n", "import numpy as np\n", "from matplotlib import pyplot as plt\n", "# Another way of writting\n", "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": null, "id": "df8ffbb1-59e4-42ce-a803-8b9c37ee25c8", "metadata": {}, "outputs": [], "source": [ "# Now you can use these modules / packages\n", "x = np.random.randn(20,1)\n", "print(x)" ] }, { "cell_type": "code", "execution_count": null, "id": "6ab7e965-e4ac-4d35-afbc-d0a0bb872706", "metadata": {}, "outputs": [], "source": [ "# Perform some calculations`\n", "y = x**2\n", "print(y)" ] }, { "cell_type": "code", "execution_count": null, "id": "83761267-266b-4efd-a166-d3792539b400", "metadata": {}, "outputs": [], "source": [ "# And plot the result\n", "plt.plot(x, y, '.', color='red', label='some function')\n", "plt.xlabel('x')\n", "plt.ylabel('x squared')\n", "plt.legend()" ] }, { "cell_type": "markdown", "id": "df430016-07e9-4f0d-83ad-209d1f3dbff5", "metadata": {}, "source": [ "## Thats it for the basics!\n", "\n", "Feel free to experiment with the examples above." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.12.7" } }, "nbformat": 4, "nbformat_minor": 5 }