{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Loops and Conditional Statements\n", "\n", "Iterate and apply conditional criteria. \n", "\n", "> **Requirements:** Make sure to understand statements as defined in the section on [Errors, Logging, and Debugging](https://hydro-informatics.com/jupyter/pyerror.html).\n", "\n", "*Python* provides two basic types of loops to iterate through objects or functions: the `for` and the `while` loop statements. Both loop types have additional options and can be combined with conditional statements. Conditional statements evaluate *boolean* arguments (`True`/`False`) using the keywords `if: ... else: ...`. This section introduces the two loop types and conditional statements as integral parts of loops.\n", "\n", "## Conditional Statements (`if` - `else`) \n", "Conditional statements open with an `if` keyword, followed by a test condition (e.g., `variable >= 2`) and action to accomplish when the test condition is `True` ([*boolean*](https://hydro-informatics.com/python-basics/pybase.html#boolean) test result). The conditional statement can be followed by the `elif` (*else if*) and/or `else` keywords, which represent alternative tests in the case that the `if` test condition was `False`. However, when the `if` statement was `True`, none of the following statements will be evaluated." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "variable_2_test = \"ice cream\"\n", "if \"cream\" in variable_2_test:\n", "\tprint(\"It's creamy, for sure.\")\n", "elif \"ice\" in variable_2_test:\n", " print(\"It's cold, ice-cold cream.\")\n", "else:\n", "\tprint(\"Anything but ice cream.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Any operator can be used in the test condition (see [operators](https://hydro-informatics.com/python-basics/pybase.html#operators)) and conditions can be nested, too.\n", "\n", "> The code blocks in the `if` - `else` statements are indented and Python uses the indentation to group statements. The same applies to loops, functions, and classes. An IDE automatically indents code, but basic text editors may not do the job. Keep in mind that wrong indentation can be an error source.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "number_of_scoops = 3\n", "if number_of_scoops <= 0:\n", "\tprint(\"Why? How can you?\")\n", "elif number_of_scoops < 4:\n", " if number_of_scoops == 1: # this is a nested if-statement\n", " print(\"One is better than nothing.\")\n", " else:\n", " print(\"That is reasonable.\")\n", "else:\n", "\tprint(\"A lot. Still reasonable. Maybe.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `for`-loop \n", "\n", "`for` loops serve for the sequential iteration through objects such as lists or arrays. `for` loops can also be complemented with `else` statements at the end (whyever you would want to do this...)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for e in range(0, 8, 2):\n", "\tprint(\"e is %d now.\" % e)\n", "\n", "flavors = [\"chocolate\", \"bread\", \"cherry\"] \n", "for index in range(len(flavors)): \n", " print(flavors[index])\n", "else:\n", " print(\" --- end of second loop.\")\n", " \n", "# produces the same\n", "for e in flavors:\n", " print(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In many cases, it is useful to iterate not only either on the iteration number (an incrementing *integer* value) or the elements of a list (e.g., a *string* value), but both simultaneously. Both the iteration step number and the list elements can be accessed with the `enumeration` method:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for iteration_step, list_element in enumerate(flavors):\n", " print(\"The list element {0} is at position number {1}.\".format(list_element, str(iteration_step)))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## `while`-loop \n", "\n", "`while` loops run until a test condition (expression) is met. Similar to the `if` statement, the test condition can be composed of just one variable or an expression including [operators](https://hydro-informatics.com/python-basics/pybase.html#operators) (e.g., `while a > b`). To modify a variable within a `while` loop, use `+=` (add amount), `-=` (subtract amount), `*=` (multiply with), or `/=` (divide by). Also `while`loops can be complemented with `else` statements.\n", "\n", "> Make sure that every `while` loop has a `break` statement. Otherwise, the script may be caught in an endless loop.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "count = 10\n", "while (count > 7):\n", " count -= 1\n", " print(\"Count down %d \" % count)\n", "else:\n", " print(\"Mission aborted.\")\n", "\n", "count = 0\n", "while True:\n", "\tprint(\"Count up: %d \" % count)\n", "\tcount += 1 # Replaces count = count + 1 - also works with -=, *= and /=\n", "\tif count > 3:\n", "\t\tbreak" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Example\n", "\n", "Use this code block to practice with data types, `for` loops and conditional `if` statements by modifying the variables `scoops` and `favorite_flavor`. Note the implementation of `try` and `except` statements ensures that whatever number of `scoops` or `favorite_flavor` you define will not crash the script." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "scoops = 2 # re-define the number of sccops\n", "favorite_flavor = \"vanilla\" # choose your favorite flavor\n", "\n", "size_scoops = {1: \"small\", 2: \"medium\", 3: \"this is too much ice cream\"}\n", "price_scoops = {1: \"3 dollars\", 2: \"5 dollars\", 3: \"your health\"}\n", "print(\"Hi,\\nI want %d scoop-s in a waffle, please.\" % scoops)\n", "\n", "try:\n", " size = \" \" + str(size_scoops[scoops])\n", " price = str(price_scoops[scoops])\n", "except ValueError:\n", " size = \"n unavailable number of scoops\"\n", " price = \"not defined\"\n", "\n", "\n", "print(\"My pleasure to serve you. You have chosen a\" + size + \" ice cream. The price is \" + price + \".\")\n", "print(\"Let me guess your favorite flavor. Say stop when I \\'m correct.\")\n", "for f in flavors:\n", " print(\"I guess your favorite flavor is %s.\" % f)\n", " if f == favorite_flavor:\n", " print(\"Stop, that\\'s it!\")\n", " if f == \"bread\":\n", " print(\"Sorry, this is not a bakery.\")\n", " break " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "> **Exercise:** Practice the application of loops with the [Hydraulics (1d)](https://hydro-informatics.com/exercises/ex-ms) exercise." ] } ], "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.9.7" } }, "nbformat": 4, "nbformat_minor": 4 }