{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "<small><small><i>\n", "All the IPython Notebooks in **Python Flow Control Statements** lecture series by Dr. Milaan Parmar are available @ **[GitHub](https://github.com/milaan9/03_Python_Flow_Control)**\n", "</i></small></small>" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python `if-elif-else` statement\n", "\n", "So far, we have presented a Boolean option for conditional statements, with each **[if statement](https://github.com/milaan9/03_Python_Flow_Control/blob/main/001_Python_if_statement.ipynb)** evaluating to either **`True`** or **`False`**. In Python, the **`if-elif-else`** condition statement has an **`elif`** keyword used to chain multiple conditions one after another." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Syntax:\n", "\n", "```python\n", "if condition-1: \n", " statement 1 \n", "elif condition-2:\n", " stetement 2 \n", "elif condition-3:\n", " stetement 3 \n", " ... \n", "else: \n", " statement \n", "```\n", "\n", "1. The **`elif`** is short for else if. It allows us to check for multiple expressions.\n", "\n", "2. If the condition for **`if`** is **`False`**, it checks the condition of the next **`elif`** block and so on.\n", "\n", "3. If all the conditions are **`False`**, the body of **`else`** is executed.\n", "\n", "4. Only one block among the several **`if-elif-else`** blocks is executed according to the condition.\n", "\n", "5. The **`if`** block can have only one **`else`** block. But it can have multiple **`elif`** blocks.\n", "\n", "<div>\n", "<img src=\"img/eif0.png\" width=\"500\"/>\n", "</div>" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:54.861499Z", "start_time": "2021-10-04T08:50:54.848803Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Zero\n" ] } ], "source": [ "# Example 1:\n", "\n", "'''In this program, we check if the number is positive or negative or zero and \n", "display an appropriate message'''\n", "\n", "num = 0\n", "\n", "# Try these two variations as well:\n", "# num = 0\n", "# num = -4.5\n", "\n", "if num > 0:\n", " print(\"Positive number\")\n", "elif num == 0:\n", " print(\"Zero\")\n", "else:\n", " print(\"Negative number\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Explanation:**\n", "\n", "When variable **`num`** is positive, **`Positive number`** is printed.\n", "\n", "If **`num`** is equal to 0, **`Zero`** is printed.\n", "\n", "If **`num`** is negative, **`Negative number`** is printed. " ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:55.015301Z", "start_time": "2021-10-04T08:50:54.876146Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "num1 is equal to num2\n" ] } ], "source": [ "# Example 2:\n", "\n", "num1, num2 = 5, 5\n", "if(num1 > num2):\n", " print(\"num1 is greater than num2\")\n", "elif(num1 == num2):\n", " print(\"num1 is equal to num2\")\n", "else:\n", " print(\"num1 is less than num2\")" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:55.153487Z", "start_time": "2021-10-04T08:50:55.019212Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "x<y\n" ] } ], "source": [ "# Example 3:\n", "\n", "x = 10\n", "y = 12\n", "if x > y:\n", " print(\"x>y\")\n", "elif x < y:\n", " print(\"x<y\")\n", "else:\n", " print(\"x=y\")" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:55.277022Z", "start_time": "2021-10-04T08:50:55.162277Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A grade\n" ] } ], "source": [ "# Example 4:\n", "\n", "grade = 96\n", "\n", "if grade >= 90:\n", " print(\"A grade\")\n", "elif grade >=80:\n", " print(\"B grade\")\n", "elif grade >=70:\n", " print(\"C grade\")\n", "elif grade >= 65:\n", " print(\"D grade\")\n", "else:\n", " print(\"Failing grade\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:55.446456Z", "start_time": "2021-10-04T08:50:55.281905Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Admin\n", "Editor\n", "Guest\n", "Wrong entry\n" ] } ], "source": [ "# Example 5:\n", "\n", "def user_check(choice):\n", " if choice == 1:\n", " print(\"Admin\")\n", " elif choice == 2:\n", " print(\"Editor\")\n", " elif choice == 3:\n", " print(\"Guest\")\n", " else:\n", " print(\"Wrong entry\")\n", "\n", "user_check(1) # Admin\n", "user_check(2) # Editor\n", "user_check(3) # Guest\n", "user_check(4) # Wrong entry" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## if-elif-else statements with logical operators\n", "\n", "We can avoid writing nested condition by using logical operator **`and`**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### if-elif-else statements `and` Logical Operator\n", "\n", "**Syntax:**\n", "\n", "```py\n", "if condition and condition:\n", " code\n", "```" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:55.556809Z", "start_time": "2021-10-04T08:50:55.453294Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A is zero\n" ] } ], "source": [ "a = 0\n", "if a > 0 and a % 2 == 0:\n", " print('A is an even and positive integer')\n", "elif a > 0 and a % 2 != 0:\n", " print('A is a positive integer')\n", "elif a == 0:\n", " print('A is zero')\n", "else:\n", " print('A is negative')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### if-elif-else statements `or` Logical Operator\n", "\n", "**Syntax:**\n", "\n", "```py\n", "if condition or condition:\n", " code\n", "```" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "ExecuteTime": { "end_time": "2021-10-04T08:50:55.708176Z", "start_time": "2021-10-04T08:50:55.559738Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Access denied!\n" ] } ], "source": [ "user = 'Arthur'\n", "access_level = 3\n", "if user == 'admin' or access_level >= 4:\n", " print('Access granted!')\n", "else:\n", " print('Access denied!')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 💻 Exercises ➞ <span class='label label-default'>List</span>\n", "\n", "### Exercises ➞ <span class='label label-default'>Level 1</span>\n", "\n", "1. Get two numbers from the user using input prompt. If **`num_1`** is greater than **`num_2`** return **`num_1`** is greater than **`num_2`**, if **`num_1`** is less **`num_2`** return **`num_1`** is smaller than **`num_2`**, else **`num_1`** is equal to **`num_2`**. Output:\n", "\n", "```sh\n", "Enter number one: 9\n", "Enter number two: 6\n", "9 is greater than 6\n", "```\n", "\n", "### Exercises ➞ <span class='label label-default'>Level 2</span>\n", "\n", "1. Write a code which gives grade to students according to theirs scores:\n", " \n", "```py\n", " 80-100, A\n", " 70-89, B\n", " 60-69, C\n", " 50-59, D\n", " 0-49, F\n", "```\n", "\n", "2. Check if the season is Autumn, Winter, Spring or Summer. \n", " - If the user input is:\n", " - September, October or November, the season is Autumn.\n", " - December, January or February, the season is Winter.\n", " - March, April or May, the season is Spring\n", " - June, July or August, the season is Summer\n", "\n", "\n", "3. The following list contains some fruits:\n", " - If a fruit doesn't exist in the list add the fruit to the list and print the modified list. If the fruit exists print **`('That fruit already exist in the list')`** \n", " \n", "```py\n", " fruits = ['banana', 'orange', 'mango', 'pear']\n", "``` \n", "\n", "\n", "### Exercises ➞ <span class='label label-default'>Level 3</span>\n", "\n", " 1. Here we have a person dictionary. Feel free to modify it!\n", " \n", "```py\n", " person={\n", " 'first_name': 'Milaan',\n", " 'last_name': 'Parmar',\n", " 'age': 96,\n", " 'country': 'Finland',\n", " 'is_marred': True,\n", " 'skills': ['Python', 'Matlab', 'R', 'C', 'C++'],\n", " 'address': {\n", " 'street': 'Space street',\n", " 'zipcode': '02210'\n", " }\n", " }\n", "```\n", "\n", " * Check if the person dictionary has skills key, if so print out the middle skill in the skills list.\n", " * Check if the person dictionary has skills key, if so check if the person has 'Python' skill and print out the result.\n", " * If a person skills has only Python and Matlab, print('He knows machine learning'), if the person skills has Python, and R print('He knows statistics'), if the person skills has C, and C++, Print('He knows software development'), else print('unknown title') - for more accurate results more conditions can be nested!\n", " * If the person is married and if he lives in Finland, print the information in the following format:\n", "\n", "```py\n", " Milaan Parmar lives in Finland. He is married.\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "hide_input": false, "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.8" }, "toc": { "base_numbering": 1, "nav_menu": {}, "number_sections": true, "sideBar": true, "skip_h1_title": false, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": false, "toc_position": { "height": "calc(100% - 180px)", "left": "10px", "top": "150px", "width": "204.797px" }, "toc_section_display": true, "toc_window_display": false }, "varInspector": { "cols": { "lenName": 16, "lenType": 16, "lenVar": 40 }, "kernels_config": { "python": { "delete_cmd_postfix": "", "delete_cmd_prefix": "del ", "library": "var_list.py", "varRefreshCmd": "print(var_dic_list())" }, "r": { "delete_cmd_postfix": ") ", "delete_cmd_prefix": "rm(", "library": "var_list.r", "varRefreshCmd": "cat(var_dic_list()) " } }, "types_to_exclude": [ "module", "function", "builtin_function_or_method", "instance", "_Feature" ], "window_display": false } }, "nbformat": 4, "nbformat_minor": 2 }