{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "(if_statement)=\n", "# If statement\n", "\n", "`if` construct allows to create cases in the code based on conditions:\n", "\n", "```\n", " if condition:\n", " # Execute some code if condition is True\n", " elif condition2:\n", " # Execute some code only if condition is False and condition2 is True\n", " else:\n", " # Execute some code only if both condition and condition2 are False\n", "```\n", " \n", "`elif` and `else` are optional blocks. Code inside each block needs to be indented.\n", "\n", "## Example use" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 is less than 12.\n", "0\n" ] } ], "source": [ "number = 10\n", "\n", "if number < 5:\n", " print(\"%g is less than 5.\" % (number))\n", "elif number < 12:\n", " print(\"%g is less than 12.\" % (number))\n", "else:\n", " print(\"%g is greater or equal to 12.\" % (number))\n", " \n", "# If statements in one line\n", "a = 1 if number == 5 else 0\n", "print(a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "(if_statement_exercises)=\n", "## Exercises\n", "\n", "---------------\n", "\n", "* **Flow control**: What is the difference between the output of the following code samples:\n", "\n", "```python\n", "a = 5\n", "\n", "if a < 5:\n", " print(\"foo\")\n", "elif a == 5:\n", " print(\"bar\")\n", "else:\n", " print(\"boom\")\n", "```\n", "\n", "```python\n", "a = 4\n", "\n", "if a < 5:\n", " print(\"foo\")\n", "elif a == 5:\n", " print(\"bar\")\n", "else:\n", " print(\"boom\")\n", "```\n", "\n", "```python\n", "a = 4\n", "if a <5:\n", " print(\"foo\")\n", "elif a == 5:\n", " print(\"bar\")\n", "\n", "print(\"boom\") \n", "```" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```{admonition} Answer\n", ":class: dropdown\n", "\n", "First: \n", " bar\n", " \n", "Second:\n", " foo\n", " \n", "Third:\n", " foo\n", " boom\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "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.7.4" } }, "nbformat": 4, "nbformat_minor": 4 }