{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "PythonForDataScience_intro.ipynb", "provenance": [], "collapsed_sections": [ "Zfms3DPGJbL-", "rhZuvfjORCEh", "rlcQJDLlFUuz", "kRjiRzYl9Xuy", "I3qwY_iVxkuX", "crVFfqHF_7Qj", "fRrO-BOOeUCE", "xEPReYdxm-E5" ] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "source": [ "These are called cells. There are 2 types of cells: code and text. We can add more cells by clicking the + buttons above!\n", "\n", "In a code cell you can type some code and then you execute the code by pressing Shift + Enter\n", "\n", "In a text cell you can also format text!\n", "# Chapter 1!\n", "Sub text here!\n", "\n", "## Sub-Header\n", "\n", "### Sub-Sub-Header" ], "metadata": { "id": "SS1aONKU9FyM" } }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "zeoHP5FokIWM" }, "execution_count": 1, "outputs": [] }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "FfYdhQ-fkI76" }, "execution_count": 1, "outputs": [] }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "gw6grf6bkJPp" }, "execution_count": 1, "outputs": [] }, { "cell_type": "markdown", "source": [ "" ], "metadata": { "id": "bmIURVp3kLfB" } }, { "cell_type": "code", "source": [ "2+2" ], "metadata": { "id": "wiVCBtg89Dz1", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "d625d75d-51e9-471a-c4a4-3d111c1b2aa8" }, "execution_count": 2, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "4" ] }, "metadata": {}, "execution_count": 2 } ] }, { "cell_type": "code", "source": [ "2+2\n", "4+4" ], "metadata": { "id": "SBBED0rE6rxn", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "59d3f317-0a0f-4dd7-c617-52f37b52abb3" }, "execution_count": 3, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "8" ] }, "metadata": {}, "execution_count": 3 } ] }, { "cell_type": "code", "source": [ "print(2+2)\n", "print(4+4)" ], "metadata": { "id": "hSZ2aNVh6r3u", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "59e22b79-2a12-4d63-f7d4-93c3e4814c13" }, "execution_count": 4, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "4\n", "8\n" ] } ] }, { "cell_type": "code", "source": [ "print('hello world!')" ], "metadata": { "id": "9JkDnOvG6zsp", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3f1a4557-3ecb-48d7-81cf-3969891917bb" }, "execution_count": 5, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "hello world!\n" ] } ] }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "iFWtrUbJCiad" }, "execution_count": 5, "outputs": [] }, { "cell_type": "code", "source": [ "print('hello world',2+2,'this is python')" ], "metadata": { "id": "isR8teAB6zu_", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "70668aee-bc05-4382-baf7-1d6a646b808d" }, "execution_count": 6, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "hello world 4 this is python\n" ] } ] }, { "cell_type": "code", "source": [ "print('hello world',2+2,'this is python',sep='')" ], "metadata": { "id": "qS7VIsa37RKx", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "8c8eef92-d487-4cda-853c-8632d2e8bdb2" }, "execution_count": 7, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "hello world4this is python\n" ] } ] }, { "cell_type": "code", "source": [ "# everything to the right of a # is not run as code, this is called a comment!\n", "2+2 # this is adding two plus two" ], "metadata": { "id": "xIoQO0ix6zxJ", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "73232415-f158-45ee-f62e-4515c3cebc7c" }, "execution_count": 8, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "4" ] }, "metadata": {}, "execution_count": 8 } ] }, { "cell_type": "code", "source": [ "# we can add strings together!\n", "print('hello'+'world')" ], "metadata": { "id": "TMuz1Mlc6zzv", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ce9aef73-2ec3-4f36-d72f-12637f59f0a6" }, "execution_count": 9, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "helloworld\n" ] } ] }, { "cell_type": "code", "source": [ "print('hello ' + ' world')" ], "metadata": { "id": "FfMWZGHRCtsz", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "49073001-1c35-4789-e280-06269cdb18c4" }, "execution_count": 10, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "hello world\n" ] } ] }, { "cell_type": "code", "source": [ "print('hello'+5)" ], "metadata": { "id": "i2VDUtLgCxPD", "colab": { "base_uri": "https://localhost:8080/", "height": 166 }, "outputId": "6945f455-ed96-4381-ebf9-a9ac520b7fd6" }, "execution_count": 11, "outputs": [ { "output_type": "error", "ename": "TypeError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'hello'\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m5\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] } ] }, { "cell_type": "markdown", "source": [ "A mobile store MobiWorld sells different mobile phones to customers. For each order that is placed, the store keeps a record of various attributes related to the mobile, like Price, Brand, RAM (GB), and Internal Storage (GB).\n", "\n", "Let's learn Python using the context of the store's data.\n" ], "metadata": { "id": "qA3wyngS6oI3" } }, { "cell_type": "markdown", "metadata": { "id": "Zfms3DPGJbL-" }, "source": [ "## 1.1 Intro to Variables" ] }, { "cell_type": "markdown", "metadata": { "id": "lJcCrrGLmUQL" }, "source": [ "First, we have to store our data to a variable that can be used to extract the stored information later. Let's take an example of how we can do that in Python.\n", "\n", "Q. Suppose the store sold an Apple iPhone (4GB, 128GB) for $900. Store this information in the variables **price**, **brand**, **ram**, and **storage**.\n" ] }, { "cell_type": "code", "metadata": { "id": "QFfVcPv3nuNp", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b617ebe1-f784-4546-ba07-cfbe465715ac" }, "source": [ "# store the price (in dollars) of the mobile in variable 'price'\n", "price = 900\n", "# print the value saved in the variable 'price'\n", "print('The price of the mobile is $',price,sep='')" ], "execution_count": 13, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The price of the mobile is $900\n" ] } ] }, { "cell_type": "code", "metadata": { "id": "PtM8OsxBpqjc", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "f3996ecc-9a95-42d5-e41e-e2e5dea438a7" }, "source": [ "# store the brand name of the mobile in variable 'brand'.\n", "brand = 'Apple'\n", "# print the value saved in the variable 'brand'\n", "print('The brand of the mobile is',brand)" ], "execution_count": 14, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The brand of the mobile is Apple\n" ] } ] }, { "cell_type": "code", "metadata": { "id": "YuF62kesqH4k", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "76fed9ae-2572-4eda-e084-394f2ad4ebe6" }, "source": [ "# store the RAM (in GB) of the mobile in variable 'ram'.\n", "ram = 4\n", "# print the value saved in the variable 'ram'\n", "print('The RAM of the mobile is', ram,'GB')" ], "execution_count": 15, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The RAM of the mobile is 4 GB\n" ] } ] }, { "cell_type": "code", "metadata": { "id": "km7ePn3WqUVk", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "fba88284-37e7-4e3c-a7ff-ec30a9f5d05b" }, "source": [ "# store the internal storage (in GB) of the mobile in variable 'storage'.\n", "storage = 128\n", "# print the value saved in the variable 'Memory'\n", "print('The internal storage of the mobile is', storage, 'GB')" ], "execution_count": 16, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The internal storage of the mobile is 128 GB\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "6Hl1V6TfC3PN" }, "source": [ "Q. Let's say the store wants to save the information on the billing status of the above phone in a boolean variable. Write the code in Python to implement the same." ] }, { "cell_type": "code", "metadata": { "id": "_jZ5ynflEGlJ", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "e14ebcc0-fd09-45ad-a5d6-6c1a23eebb3a" }, "source": [ "# a special type of variable stores just True/False values. This is called a boolean variable.\n", "# create a boolean variable 'is_billed' to save the billing information\n", "is_billed = True\n", "print(is_billed)" ], "execution_count": 17, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "True\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "3V2CNbizt63k" }, "source": [ "The value that we store in a variable can be a number or a set of characters or a boolean variable (True/False). For example, a price is a number while the brand name is a set of characters which is also known as a string in python. Whenever we store a value in a variable, Python automatically assigns a data type to that variable based on the value. It also allows us to check the data type of the variable.\n", "\n", "Q. Check the data type of the variables **price**, **brand**, **ram**, and **storage**" ] }, { "cell_type": "code", "metadata": { "id": "g4KOBpxyvbIR", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "97d5d8b1-dbf0-4af9-ea4d-c09bfb2591e5" }, "source": [ "# check the data-type using the type function\n", "type(price)" ], "execution_count": 18, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "int" ] }, "metadata": {}, "execution_count": 18 } ] }, { "cell_type": "code", "metadata": { "id": "M8vCNgGavtIw", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "74b15c50-043e-4936-fbf9-a1e0023f7cae" }, "source": [ "# check the data-type using the type function\n", "type(brand)" ], "execution_count": 19, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "str" ] }, "metadata": {}, "execution_count": 19 } ] }, { "cell_type": "code", "metadata": { "id": "4Tur0cIAwTxr", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "d9f0f2c8-f6a6-4cc3-8a19-d894c44b840a" }, "source": [ "# check the data-type using the type function\n", "type(ram)" ], "execution_count": 20, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "int" ] }, "metadata": {}, "execution_count": 20 } ] }, { "cell_type": "code", "metadata": { "id": "r0kULhRIwVbP", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "94c9d25b-2c12-4474-949d-166692d7a6ce" }, "source": [ "# check the data-type using the type function\n", "type(storage)" ], "execution_count": 21, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "int" ] }, "metadata": {}, "execution_count": 21 } ] }, { "cell_type": "code", "metadata": { "id": "Q_81HC3LFF8_", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3f65f94d-2665-48e1-9eb5-504555baa225" }, "source": [ "# check the data-type using the type function\n", "type(is_billed)" ], "execution_count": 22, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "bool" ] }, "metadata": {}, "execution_count": 22 } ] }, { "cell_type": "markdown", "metadata": { "id": "MP4Csswyq1mG" }, "source": [ "Q. Let's say a customer buys two Apple iPhones (4GB, 128GB) at a price of $900 each. What will be the total bill that the customer has to pay?" ] }, { "cell_type": "code", "metadata": { "id": "PUv9ztT6sG3i", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ba06c164-32df-4a91-dc00-7fd53541e9e3" }, "source": [ "# calcuate the total bill and store it in variable 'bill'\n", "bill = price + price\n", "# the same result can be achieved by multiplication.\n", "bill = price*2\n", "print('The bill amount is $',bill,sep='')" ], "execution_count": 23, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The bill amount is $1800\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "t9Xp42rvP5lJ" }, "source": [ "Q. Let's say the store provides a discount of \\$15 dollars on the Apple iPhone (4GB, 128GB) that costs $900. What will be the price of the iPhone after the discount?\n" ] }, { "cell_type": "code", "metadata": { "id": "qjha3bvzQovj", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "e24b8c0c-b30e-4b16-a221-bf906075c8d1" }, "source": [ "# store the price (in dollars) of the mobile in variable 'price'\n", "price = 900\n", "# store the discount amount in variable 'discount'\n", "discount = 15\n", "# calculate the discounted price\n", "price_after_discount = price - discount\n", "print('The price of the iPhone after the discount is $',price_after_discount,sep='')" ], "execution_count": 24, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The price of the iPhone after the discount is $885\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "zZvOG69cVKYA" }, "source": [ "Q. Let's say a customer buys two Apple iPhones (4GB, 128GB) and pays a total bill of \\$1800. Write the Python code to find the price of an Apple iPhone." ] }, { "cell_type": "code", "metadata": { "id": "jd7Z5MDBWXkY", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b19c4cbb-1ffa-4e13-bb34-d0ee08966d66" }, "source": [ "# store the bill (in dollars) of the two mobiles in variable 'bill'\n", "bill = 1800\n", "# calculate the price of one mobile\n", "price = bill / 2\n", "print('The price of an Apple iPhone is $',price,sep='')" ], "execution_count": 25, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The price of an Apple iPhone is $900.0\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "G1LuAO-rRjhK" }, "source": [ "Q. Let's say a customer buys x numbers of Apple iPhones (4GB, 128GB) for $900 each. The total bill that the customer pays is \\$3600. Write the Python code to find the value of x." ] }, { "cell_type": "code", "metadata": { "id": "UaiRRd3WReW6", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "dee71494-69a9-43a6-97c1-3d79efc0d1f1" }, "source": [ "# store the bill (in dollars) of the mobile in variable 'bill'\n", "bill = 3600\n", "# store the price (in dollars) of the mobile in variable 'price'\n", "price = 900\n", "# calculate the number of iPhones that the customer buys\n", "x = bill // price\n", "# double divided forces the answer to be an integer!\n", "print('The customer buys', x, 'Apple iPhones')" ], "execution_count": 26, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The customer buys 4 Apple iPhones\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "cG-aP2YlFNzB" }, "source": [ "Q. Suppose the store plans to provide a 4.5% discount on the Apple iPhone. What will be the discounted price of the mobile?" ] }, { "cell_type": "markdown", "metadata": { "id": "3fpYu_Z8Ndf0" }, "source": [ "**Type Conversion**: The process of converting one data type to another data type is called type conversion. \n", "\n", "In Python, we can perform two types of type conversion.\n", "\n", "1. Implicit Type Conversion - Here, Python automatically converts one data type to another in order to avoid data loss.\n", "\n", "2. Explicit Type Conversion - Here, the user can convert the data type of a variable to the required data type by using the in-built functions int(), float(), str(), etc.\n" ] }, { "cell_type": "code", "metadata": { "id": "RmmOkRrwG6ac", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "89184212-8eb2-4a24-9f87-ac48387be698" }, "source": [ "# store the price (in dollars) of the mobile in variable 'price'\n", "price = 900\n", "# calculate the discount amount\n", "discount = price * 0.045\n", "# calculate the discounted price\n", "discounted_price = price - discount\n", "print('The discounted price of the iPhone is ' + str(discounted_price))" ], "execution_count": 27, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The discounted price of the iPhone is 859.5\n" ] } ] }, { "cell_type": "code", "source": [ "type(discounted_price)" ], "metadata": { "id": "usYUYXiOCdVt", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b999ecdf-ba6f-4fb0-dc30-3cbac0c5ac6a" }, "execution_count": 28, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "float" ] }, "metadata": {}, "execution_count": 28 } ] }, { "cell_type": "markdown", "metadata": { "id": "2SrYvKgAZv2c" }, "source": [ "Now, let's check the data type of the variables 'discount' and 'price'" ] }, { "cell_type": "code", "metadata": { "id": "5vU-mAkiZ92S", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "90eedeaa-9184-4592-d7ec-db9fe7493a62" }, "source": [ "print('The data type of variable price is',type(price))\n", "print('The data type of variable discount is',type(discount))" ], "execution_count": 29, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The data type of variable price is \n", "The data type of variable discount is \n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "q05dBOmTwXuE" }, "source": [ "As we can see, the data type of 'discount' is float as Python is implicitly converting the lower data type to a higher data type to avoid data loss.\n", "\n", "Suppose we want to add the variables **brand**, **ram**, and **storage**. \n", "\n", "Will the implicit conversion work?\n", "\n", "Let's try it!" ] }, { "cell_type": "code", "metadata": { "id": "F-JdovnFdDpu", "colab": { "base_uri": "https://localhost:8080/", "height": 166 }, "outputId": "856db8c1-437b-4ffd-d41a-15eaf6d255ab" }, "source": [ "print(brand + ' ' + ram + 'GB')" ], "execution_count": 30, "outputs": [ { "output_type": "error", "ename": "TypeError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mbrand\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m' '\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mram\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m'GB'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "R6NNDgIKdR8T" }, "source": [ "As we can see from the output, the TypeError is being raised which indicates that Python is not able to use Implicit Conversion in such conditions.\n", "\n", "But, we can do an explicit conversion for such cases." ] }, { "cell_type": "code", "metadata": { "id": "sSG3cdv0w630", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "4df36bfa-6f4c-4601-9123-bac029e87ce0" }, "source": [ "brand + ' ' + str(ram) + 'GB'" ], "execution_count": 31, "outputs": [ { "output_type": "execute_result", "data": { "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" }, "text/plain": [ "'Apple 4GB'" ] }, "metadata": {}, "execution_count": 31 } ] }, { "cell_type": "markdown", "metadata": { "id": "rhZuvfjORCEh" }, "source": [ "## 1.2 Data Structures\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "3qxT-ewKRNhU" }, "source": [ "**MobiWorld store has provided a snapshot of the details of mobile phones sold by them.**\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "jyuWMd1kT8oE" }, "source": [ "| Brand | RAM (in GB) | Memory (in GB) | Price (in dollars) |\n", "| --- | --- | --- | --- |\n", "| Apple | 4 | 128 | 900 |\n", "| Samsung | 12 | 128 | 899 |\n", "| LG | 8 | 64 | 600 |\n", "| Apple | 8 | 128 | 1000 |\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "OUF9q0yGUdKP" }, "source": [ "We know how to create a variable to store the brand name." ] }, { "cell_type": "code", "metadata": { "id": "VCc3NBUoUbew", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "71e6a3ae-ce53-46f2-fa1b-8e3845db410d" }, "source": [ "Brand = 'Apple'\n", "print(Brand)" ], "execution_count": 32, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Apple\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "X1G0u69v4YKD" }, "source": [ "#### List" ] }, { "cell_type": "markdown", "metadata": { "id": "N5KIeBCPUxlY" }, "source": [ "Let's create a variable that will store all the brand names given in the above table. This can be achieved using the 'list' data struture in Python. \n", "\n", "Lists are used to store the data items inside square brackets [] where each data item is separated by a comma (,)" ] }, { "cell_type": "code", "metadata": { "id": "NdRGH5VVULgp", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "37c65129-0eef-4b40-c244-8e4376d5ea6c" }, "source": [ "# create a list \n", "brand_list = ['Apple', 'Samsung', 'LG', 'Apple']\n", "brand_list" ], "execution_count": 33, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['Apple', 'Samsung', 'LG', 'Apple']" ] }, "metadata": {}, "execution_count": 33 } ] }, { "cell_type": "code", "metadata": { "id": "Gs5hLI-zVybq", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "5c827bb9-5d57-4dde-a8b0-c6a633e7aa33" }, "source": [ "# check the type of the variable 'brand_list'\n", "type(brand_list)" ], "execution_count": 34, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "list" ] }, "metadata": {}, "execution_count": 34 } ] }, { "cell_type": "markdown", "metadata": { "id": "f8k9SsafaAh5" }, "source": [ "Let's create lists for other attributes as well." ] }, { "cell_type": "code", "metadata": { "id": "pz296Fu9aKkD" }, "source": [ "ram_list = [4, 12, 8, 8]\n", "storage_list = [128, 128, 64, 128]\n", "price_list = [900, 899, 600, 1000]" ], "execution_count": 35, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "uyvz9uRCa8Vw", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "7e5529e6-9261-433e-d101-80878bfb1047" }, "source": [ "# let's print the lists we created\n", "print('RAM List:', ram_list)\n", "print('Storage List:', storage_list)\n", "print('Price List:', price_list)" ], "execution_count": 36, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "RAM List: [4, 12, 8, 8]\n", "Storage List: [128, 128, 64, 128]\n", "Price List: [900, 899, 600, 1000]\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "gcUOproLbUrd" }, "source": [ "Now, we have created lists for all attributes with the provided data. There are various operations that can be performed on lists to extract information from the data. Let's understand a few important methods by answering some questions." ] }, { "cell_type": "markdown", "metadata": { "id": "XZ-I7h-mcTfQ" }, "source": [ "Q. How many records are stored in the list brand_list?" ] }, { "cell_type": "markdown", "metadata": { "id": "8bMPW9ltctr-" }, "source": [ "\n", "\n", "* len() is an in-built function in Python that provides the count of elements inside a list. In-built functions are functions that are already defined in the Python framework to perform a task.\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "C_aMKnD9cn29", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "9d05bbf7-bc7e-47d7-c4b0-628ab4593cdd" }, "source": [ "len(brand_list)" ], "execution_count": 37, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "4" ] }, "metadata": {}, "execution_count": 37 } ] }, { "cell_type": "markdown", "metadata": { "id": "ucTw2ifG-glr" }, "source": [ "We have 4 records " ] }, { "cell_type": "markdown", "metadata": { "id": "6z_HEP48dBfH" }, "source": [ "Q. Find the minimum and maximum price among the mobile phones sold by the store." ] }, { "cell_type": "markdown", "metadata": { "id": "UqCrWx7d_QD-" }, "source": [ "* min() and max() are in-built functions in Python that calculates the minimum and maximum values among the items in a list (or some other data types)." ] }, { "cell_type": "code", "metadata": { "id": "Jlj1uxuNd-hw", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "8fd0e9d9-1445-4d39-d5fd-77c58eb83d79" }, "source": [ "# minimum price\n", "min_price = min(price_list)\n", "print('The minimum price is $' + str(min_price))\n", "# maximum price\n", "max_price = max(price_list)\n", "print('The maximum price is $' + str(max_price))" ], "execution_count": 38, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The minimum price is $600\n", "The maximum price is $1000\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "aIihYl6veE6t" }, "source": [ "* The minimum and maximum prices are \\$600 and $1000 respectively. \n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "XNuquyGf5CPM" }, "source": [ "As a list may contain a large number of items in it, there should be a way to access the item that we want. This is achieved by indexing the list to access the required item.\n", "\n", "Q. Print the third item in the list ram_list." ] }, { "cell_type": "markdown", "metadata": { "id": "uqHY5ehU5HKQ" }, "source": [ "* Indexing in list is done by specifying the index inside square brackets. In python, indexing starts with 0. That is, the first item has the index 0, the second has the index 1 and so on." ] }, { "cell_type": "code", "metadata": { "id": "_amZFVGQ5LzK", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "aef376d3-497b-4b4d-f9a8-3178c61cd997" }, "source": [ "# indexing to get the third item in ram_list\n", "print(ram_list[2])" ], "execution_count": 39, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "8\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "010MLnYv5RF5" }, "source": [ "Q. Print the first three items from the list price_list." ] }, { "cell_type": "markdown", "metadata": { "id": "a5WRJWAz5T3q" }, "source": [ "* We can also select a range of indices to access more than 1 item. This can be done by using a colon (:) between the start and stop index" ] }, { "cell_type": "code", "metadata": { "id": "31v2bdjK5fsV", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "61ef189c-e807-454f-fe90-12462daff060" }, "source": [ "# first three items in price_list\n", "print(price_list[0:3])" ], "execution_count": 40, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[900, 899, 600]\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "Y-UXUhxZ5jPL" }, "source": [ "Notice that in such an indexing, the output includes the item at the start index (index 0) but excludes the item at the stop index (index 3). The index [0:3] has included the items at indices 0, 1 and 2" ] }, { "cell_type": "markdown", "metadata": { "id": "IQ7KaeJE5m7U" }, "source": [ "Q. Print the last item in the list brand_list." ] }, { "cell_type": "markdown", "metadata": { "id": "KSsQP0g75p2K" }, "source": [ "* The last item can also be accessed using its index. But, if the list is too large, counting the index for the last item may not be the best way. Here's how the last item can be accessed for any list." ] }, { "cell_type": "code", "metadata": { "id": "NwovAGAn5rzu", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3fa51aa1-662c-48a7-e1c5-5a618a5acef1" }, "source": [ "# last item in brand_list\n", "print(brand_list[-1])" ], "execution_count": 41, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Apple\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "f1Omoi3ThWZS" }, "source": [ "The Store finds out that for the last record in the data, the brand name provided was not correct. \n", "\n", "Q. Remove the last element from the list brand_list." ] }, { "cell_type": "markdown", "metadata": { "id": "3PLiR1eriB0r" }, "source": [ "* pop() is a list method that removes the item at the given index and returns the removed item . If the index is not specified, by default, it removes the last element. To confirm we can check the list again." ] }, { "cell_type": "code", "metadata": { "id": "GLU8d4VLhgBo", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "d5bcf8cb-8ed1-4e68-c9ec-5def63f622d2" }, "source": [ "brand_list.pop()" ], "execution_count": 42, "outputs": [ { "output_type": "execute_result", "data": { "application/vnd.google.colaboratory.intrinsic+json": { "type": "string" }, "text/plain": [ "'Apple'" ] }, "metadata": {}, "execution_count": 42 } ] }, { "cell_type": "code", "metadata": { "id": "GKlrRebCkcSl", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3897ee66-6568-4dc5-9ad8-5751c7309c35" }, "source": [ "brand_list" ], "execution_count": 43, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['Apple', 'Samsung', 'LG']" ] }, "metadata": {}, "execution_count": 43 } ] }, { "cell_type": "markdown", "metadata": { "id": "wq_76ZPjkdpN" }, "source": [ "As we can see the last element got removed. Now, the Store informs that the correct brand name should be \"Motorola'.\n", "\n", "Q. Insert 'Motorola' to the list brand_list\n", "\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "YkMJ6BX86fup" }, "source": [ "* The append() method adds a single item to an existing list." ] }, { "cell_type": "code", "metadata": { "id": "OWRzQJ5FmJMq", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "420ce930-77c6-44cb-e5f2-f17dcd188367" }, "source": [ "brand_list.append('Motorola')\n", "brand_list" ], "execution_count": 44, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['Apple', 'Samsung', 'LG', 'Motorola']" ] }, "metadata": {}, "execution_count": 44 } ] }, { "cell_type": "code", "source": [ "brand_list[3] = 'Apple'\n", "print(brand_list)\n" ], "metadata": { "id": "qxGjoIqOAm-l", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "494c820b-d60c-4880-b4db-f0db13ffe338" }, "execution_count": 45, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['Apple', 'Samsung', 'LG', 'Apple']\n" ] } ] }, { "cell_type": "code", "source": [ "brand_list[3] = 'Motorola'\n", "brand_list" ], "metadata": { "id": "ogGGnKahAzr8", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "224569fb-d03f-4d0b-d21a-458b08a70440" }, "execution_count": 46, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "['Apple', 'Samsung', 'LG', 'Motorola']" ] }, "metadata": {}, "execution_count": 46 } ] }, { "cell_type": "markdown", "metadata": { "id": "EwtvxH6HmLvQ" }, "source": [ "We have succesfully corrected the list now." ] }, { "cell_type": "markdown", "metadata": { "id": "rlcQJDLlFUuz" }, "source": [ "#### Tuple" ] }, { "cell_type": "markdown", "metadata": { "id": "cCG1aiFWFXcY" }, "source": [ "Now that you have learned about lists, you know that data can be modified and altered in a list, making it a mutable data structure. Sometimes, you might want to store data which should not be altered, for example storage. The storage in a mobile phone is in terms of powers of 2, that is, 32 GB, 64 GB, 128 GB, etc. You do not want to alter the number 32 and change it to 30.\n", "\n", "Q. Store the storage specifications 32/64/128/256 as an immutable variable." ] }, { "cell_type": "code", "metadata": { "id": "asSlUBP6Iep3", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "43d33f87-2e62-434a-90b0-d94f8f68047f" }, "source": [ "storage = (32,64,128,256)\n", "print(storage)" ], "execution_count": 47, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "(32, 64, 128, 256)\n" ] } ] }, { "cell_type": "code", "metadata": { "id": "5HOrggg8JBBx", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b29fadd6-9955-46ce-93c8-ec45cb3bcd60" }, "source": [ "type(storage)" ], "execution_count": 48, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "tuple" ] }, "metadata": {}, "execution_count": 48 } ] }, { "cell_type": "markdown", "metadata": { "id": "RkusDTP8I4FJ" }, "source": [ "* The above data structure structure is called a tuple. A tuple in Python is similar to a list. The difference between the two is that unlike lists we cannot change the elements of a tuple once it is assigned. " ] }, { "cell_type": "markdown", "metadata": { "id": "PXRJO7GCJqp3" }, "source": [ "Indexing in tuple is similar to indexing in lists. \n", "\n", "Q. Print the second item in the tuple **storage**" ] }, { "cell_type": "code", "metadata": { "id": "MPV67Nb7J1xC", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "25ed3947-a421-4754-86ef-ebda2a3462a6" }, "source": [ "print(storage[1])" ], "execution_count": 49, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "64\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "4DYux3LMMib_" }, "source": [ "Let's try changing the second item to 60 and see if it works." ] }, { "cell_type": "code", "metadata": { "id": "dBOc6JBkMnjD", "colab": { "base_uri": "https://localhost:8080/", "height": 183 }, "outputId": "34a4dbea-4302-4698-bb06-284584ac5304" }, "source": [ "# try changing an item in a tuple\n", "storage[1]=60" ], "execution_count": 50, "outputs": [ { "output_type": "error", "ename": "TypeError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;31m# try changing an item in a tuple\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mstorage\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;36m60\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" ] } ] }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "EVpfK94zAjgu" }, "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "U_JDEPZmMwbn" }, "source": [ "As can be seen from the TypeError, items cannot be altered in a tuple." ] }, { "cell_type": "markdown", "metadata": { "id": "kRjiRzYl9Xuy" }, "source": [ "### Dictionary" ] }, { "cell_type": "markdown", "metadata": { "id": "2sGaZr6V6xz-" }, "source": [ "Lists are great for storing data for a single attribute. But, we might want to add more information about the items in a variable. Suppose the store wants to store the attributes **brand, ram, storage,** and **price** in a single variable.\n", "\n", "Q. Store the attributes of an Apple iPhone (4GB, 128GB) of price of $800 in a single variable." ] }, { "cell_type": "code", "metadata": { "id": "4cwMCttF6yfe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b7f9db90-65df-4e57-ea10-a196400d7313" }, "source": [ "# creating a dictionary\n", "attributes = {\n", " 'Brand':'Apple', \n", " 'RAM (in GB)':4, \n", " 'Storage (in GB)':128, \n", " 'Price (in $)':800\n", " }\n", "print(attributes)" ], "execution_count": 51, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{'Brand': 'Apple', 'RAM (in GB)': 4, 'Storage (in GB)': 128, 'Price (in $)': 800}\n" ] } ] }, { "cell_type": "code", "metadata": { "id": "MRBEI4Cq6yon", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "d5f6a9fc-dce3-41af-b66c-45946ca238e6" }, "source": [ "type(attributes)" ], "execution_count": 52, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "dict" ] }, "metadata": {}, "execution_count": 52 } ] }, { "cell_type": "markdown", "metadata": { "id": "LZNjeZOl6yuX" }, "source": [ "* The above data structure is called a dictionary. Dictionaries are used to store data values in key:value pairs. Dictionaries are written with curly brackets, and have keys and values" ] }, { "cell_type": "markdown", "metadata": { "id": "tl9LAqoH6yzS" }, "source": [ "Q. Extract the price from the dictionary attributes." ] }, { "cell_type": "code", "metadata": { "id": "CzHdoQlB6y3v", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "04e32d3b-3611-4730-de9c-817c12edee58" }, "source": [ "# extract information from dictionary\n", "print(attributes['Price (in $)'])" ], "execution_count": 53, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "800\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "6NIP3jxK6y74" }, "source": [ "* For the above pair, 'Price (in $)' is the key and 800 is the value. \n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "PCVO_dye6y_7" }, "source": [ "Dictionary items are ordered, changeable, and does not allow duplicates.\n", "\n", "Q. Change the price in attributes to 900" ] }, { "cell_type": "code", "metadata": { "id": "TKkiBcId6zEe", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "d1147b12-0774-4bff-feac-c0d7adceb2a2" }, "source": [ "attributes['Price (in $)'] = 900\n", "print(attributes)" ], "execution_count": 54, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{'Brand': 'Apple', 'RAM (in GB)': 4, 'Storage (in GB)': 128, 'Price (in $)': 900}\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "45krqXL96zIl" }, "source": [ "Now, that you have learned how to create a dictionary, let's store data for multiple mobile phones in it. The values in a dictionary can also be a list to store information for more than one product.\n", "\n", "Q. Create a dictionary **products** for storing the attributes of 4 different mobile phones." ] }, { "cell_type": "code", "metadata": { "id": "NsoJ2cyA6zMw", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "5e302147-529f-4080-c010-88f1df3ed4d8" }, "source": [ "# creating a dictionary for storing data.\n", "products = {\n", " 'Brand':brand_list, \n", " 'RAM (in GB)':ram_list, \n", " 'Storage (in GB)':storage_list, \n", " 'Price (in $)':price_list\n", " }\n", "print(products)" ], "execution_count": 55, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "{'Brand': ['Apple', 'Samsung', 'LG', 'Motorola'], 'RAM (in GB)': [4, 12, 8, 8], 'Storage (in GB)': [128, 128, 64, 128], 'Price (in $)': [900, 899, 600, 1000]}\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "kKJpHALM7PXY" }, "source": [ "Using a dictionary, we have stored a lot of information in a single variable." ] }, { "cell_type": "markdown", "metadata": { "id": "hoJ8bnAC7O1L" }, "source": [ "Q. Extract the keys and values from the dictionary **products**" ] }, { "cell_type": "markdown", "metadata": { "id": "H49Xs3EL7V4T" }, "source": [ "* keys() and values() are methods of a dictionary to extract the lists of dictionary keys and dictionary values respectively." ] }, { "cell_type": "code", "metadata": { "id": "n6neMTb47YGT", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "5367aa69-c105-4d98-da86-011bdefb3ba4" }, "source": [ "# keys of a dictionary\n", "keys = products.keys()\n", "print('The keys of the dictionary are :\\n',keys)\n", "# values of a dictionary\n", "values = products.values()\n", "print('The values of the dictionary are :\\n', values)" ], "execution_count": 56, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The keys of the dictionary are :\n", " dict_keys(['Brand', 'RAM (in GB)', 'Storage (in GB)', 'Price (in $)'])\n", "The values of the dictionary are :\n", " dict_values([['Apple', 'Samsung', 'LG', 'Motorola'], [4, 12, 8, 8], [128, 128, 64, 128], [900, 899, 600, 1000]])\n" ] } ] }, { "cell_type": "code", "source": [ "products['RAM (in GB)'][1]" ], "metadata": { "id": "lTsHd_OBGhIQ", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "23d034b0-6792-45c1-ed0c-8541ef2f9e25" }, "execution_count": 57, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "12" ] }, "metadata": {}, "execution_count": 57 } ] }, { "cell_type": "markdown", "metadata": { "id": "I3qwY_iVxkuX" }, "source": [ "## 1.3 Conditional Statements" ] }, { "cell_type": "markdown", "metadata": { "id": "cQo-OvN_ygtR" }, "source": [ "Suppose a customer is planning to buy a mobile phone but has a limited budget. Thus, his decision to buy is based on the condition that the price comes under his budget. Let's say his budget is $600.\n", "\n", "Q. Write a code in Python that prints whether the customer can buy the iPhone or not based on his budget." ] }, { "cell_type": "markdown", "metadata": { "id": "qg2mxm6C2VEe" }, "source": [ "Sometimes we want to execute a block of code based on a particular condition.\n", "In these types of situations, we write conditional statements. \n", "\n", "The if-else statement in Python can be used for decision-making. The general syntax of an if-else statement is:\n", "\n", "```\n", "if (test expression):\n", " Body of if\n", "else:\n", " Body of else\n", "```\n", "\n", "Python is a tabbed based language, so we need to be VERY careful about tabs!!!\n" ] }, { "cell_type": "code", "metadata": { "id": "V8z790Jc0pNQ", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "256aed9f-dbb9-4de1-8588-6a6dba4ae083" }, "source": [ "# define the budget price\n", "budget = int(input('Enter your budget(in dollars): '))\n", "\n", "# if-else statement\n", "if price <= budget:\n", " print('Congrats! You can buy the Iphone')\n", "else:\n", " print('Sorry! The mobile price is more than your budget')" ], "execution_count": 58, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter your budget(in dollars): 100\n", "Sorry! The mobile price is more than your budget\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "dUm645mL3xfe" }, "source": [ "If there are multiple conditions, we may use another conditional statement called if-elif-else statement. The general syntax of the if-elif-else statement is:\n", "\n", "```\n", "if (test expression):\n", " Body of if\n", "elif (test expression):\n", " Body of elif\n", "else: \n", " Body of else\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "mBwaTNNJ97yi" }, "source": [ "Q. Suppose the price of the 32 GB, 64 GB, and 128 GB iPhones are \\$600, \\$700, and \\$900 respectively. Write a conditional statement to print the price based on the internal storage of the phone." ] }, { "cell_type": "code", "metadata": { "id": "QdJzMWMn_QTD", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "3e12980f-e011-4cbe-b6e3-66d7252651ee" }, "source": [ "Memory = int(input('Enter the memory: '))\n", "\n", "if Memory == 32:\n", " print('The price of the phone is $600')\n", "elif Memory == 64:\n", " print('The price of the phone is $700')\n", "elif Memory ==128:\n", " print('The price of the phone is $900')\n", "else:\n", " print('Please enter a valid memory requirement')" ], "execution_count": 59, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter the memory: 64\n", "The price of the phone is $700\n" ] } ] }, { "cell_type": "code", "source": [ "" ], "metadata": { "id": "5FdEMXl_vs69" }, "execution_count": 59, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "crVFfqHF_7Qj" }, "source": [ "## 1.4 Looping Statements\n" ] }, { "cell_type": "markdown", "metadata": { "id": "02kfQy3pKSLz" }, "source": [ "\n", "\n", "\n", "Suppose the store wants to check the price of the Apple iPhone (4GB, 128GB) after providing 5%, 10%, 15%, and 20% discounts respectively. Instead of calculating the discounted prices multiple times, looping statements can be used to achieve this.\n", "\n", "Q. Write a code in Python that prints the discounted price for each of the above-mentioned discounts.\n" ] }, { "cell_type": "markdown", "metadata": { "id": "XimtS0PyirT9" }, "source": [ "Before jumping into the concept of looping, let's have a look at the range() function in Python.\n", "\n", "The range() method returns an immutable sequence of numbers between the given start integer to the stop integer." ] }, { "cell_type": "code", "source": [ "print(range(6))" ], "metadata": { "id": "lFAxNkQeJ6Wi", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "fc08fad2-4092-428f-915d-ddc0d52c1aab" }, "execution_count": 60, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "range(0, 6)\n" ] } ] }, { "cell_type": "code", "source": [ "print(list(range(6)))" ], "metadata": { "id": "wdUJOuOSL7YZ", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "d3d66e58-d381-4942-e197-bcd613efe41d" }, "execution_count": 61, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[0, 1, 2, 3, 4, 5]\n" ] } ] }, { "cell_type": "code", "source": [ "print(list(range(2,6)))" ], "metadata": { "id": "vtLslStgL-cY", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "5f78c19a-e08a-4431-d7ce-c6268b06b38f" }, "execution_count": 62, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[2, 3, 4, 5]\n" ] } ] }, { "cell_type": "code", "metadata": { "id": "btIlmzGVmgmV", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "38e046d1-2bc4-47ef-dd69-84c96fa5515e" }, "source": [ "print(list(range(6, 14, 2)))" ], "execution_count": 63, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[6, 8, 10, 12]\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "wColSzouLhq7" }, "source": [ "Loops are used in Python to iterate over a sequence.\n", "\n", "The syntax of the 'for loop' is:\n", "\n", "```\n", "for iterator_var in sequence:\n", " statements(s)\n", "```\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "_1yuJc2JAhqD", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "6c190a85-9c1a-4286-aeb9-acb60e5dfd08" }, "source": [ "# store the price (in dollars) of the mobile in variable 'Price'.\n", "price = 900\n", "# start the for loop\n", "for i in range(5, 21, 5):\n", " # calculate the discount amount\n", " discount = price * (i / 100)\n", " # calculate the discounted price\n", " discounted_price = price - discount\n", " # print the discounted price\n", " print('The price after providing ', i, ' percent discount is $', discounted_price,sep='')" ], "execution_count": 64, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The price after providing 5 percent discount is $855.0\n", "The price after providing 10 percent discount is $810.0\n", "The price after providing 15 percent discount is $765.0\n", "The price after providing 20 percent discount is $720.0\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "VtgR0jG1vuO7" }, "source": [ "We can also use the while loop to iterate over a sequence. The syntax of the 'while loop' is:\n", "\n", "```\n", "while condition:\n", " statements(s)\n", "```\n", "\n", "Let's try to solve the above question using 'while' loops." ] }, { "cell_type": "code", "metadata": { "id": "9PYkcD-XQKfu", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "42103cbf-15a4-4c8d-d092-1af3040f7fb4" }, "source": [ "# store the price (in dollars) of the mobile in variable 'Price'.\n", "Price = 900\n", "# set the value of i to 5\n", "i = 5\n", "# start the while loop\n", "while i <= 20:\n", " # calculate the discount amount\n", " discount = Price * (i / 100)\n", " # calculate the discounted price\n", " discounted_price = Price - discount\n", " # print the discounted price\n", " print('The price after providing ',i, ' percent discount is $', discounted_price,sep='')\n", " # increase the value of i by 5\n", " i += 5" ], "execution_count": 65, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "The price after providing 5 percent discount is $855.0\n", "The price after providing 10 percent discount is $810.0\n", "The price after providing 15 percent discount is $765.0\n", "The price after providing 20 percent discount is $720.0\n" ] } ] }, { "cell_type": "code", "source": [ "i" ], "metadata": { "id": "sAWSbODZWds_", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "67a35ab6-8867-4c11-830f-b7aef3d5bba6" }, "execution_count": 66, "outputs": [ { "output_type": "execute_result", "data": { "text/plain": [ "25" ] }, "metadata": {}, "execution_count": 66 } ] }, { "cell_type": "markdown", "source": [ "## 1.5 List Comprehensions" ], "metadata": { "id": "fRrO-BOOeUCE" } }, { "cell_type": "markdown", "source": [ "MobiWorld has decided to provide an instant discount of 5% on all their products during the upcoming sale. We want to check the discounted prices of the products.\n", "\n", "We already have the `price_list` with us. Let's use it to get the discounted prices." ], "metadata": { "id": "sBIOrOMSzXl9" } }, { "cell_type": "markdown", "source": [ "One way of creating a discounted price list is by looping over the elements of `price_list`, subtracting the discount from the price, and adding it one at a time to a new list `discounted_price_list`." ], "metadata": { "id": "4q_35zrET3LJ" } }, { "cell_type": "code", "source": [ "discounted_price_list=[]\n", "\n", "for x in price_list:\n", " discounted_price = x - (x*(5/100))\n", " discounted_price_list.append(discounted_price)\n", "\n", "print(discounted_price_list)" ], "metadata": { "id": "DahV8ZZcebRV", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "0ffbb97b-daf3-4d9c-dcce-61b57de2cacb" }, "execution_count": 67, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[855.0, 854.05, 570.0, 950.0]\n" ] } ] }, { "cell_type": "markdown", "source": [ "An equivalent way of obtaining the same result is by using **list comprehensions**.\n", "\n", "* List comprehension is a type of control structure for creating a list from an existing iterable (like tuples, strings, arrays, lists, etc).\n", "* They offer a shorter and more appealing syntax and are often faster than explicit for loops in creating a list from an existing iterable." ], "metadata": { "id": "F0iCJHIV1cx_" } }, { "cell_type": "code", "source": [ "discounted_price_list = [x - (x*(5/100)) for x in price_list]\n", "print(discounted_price_list)" ], "metadata": { "id": "2rIb7zzcxTVI", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "4ba54a65-0ccc-437d-db82-125fe5df63e3" }, "execution_count": 68, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "[855.0, 854.05, 570.0, 950.0]\n" ] } ] }, { "cell_type": "markdown", "source": [ "Let's breakdown the syntax of the above list comprehension. There are three parts:\n", "1. `[ ]`: The outer square brackets tells that we are creating a list\n", "2. `x-(x*(5/100)`: The expression to evaluate or the computation to perform\n", "3. `for x in price_list`: The iterable from which elements (x) will be fetched" ], "metadata": { "id": "0g10KPzb2hH1" } }, { "cell_type": "markdown", "source": [ "Customers often want to check whether any of the discounted prices during the sale are within their budget.\n", "\n", "Let's help the store display the same based on the budget mentioned by the customer by comparing the discounted price with the budget for each of the four mobile phone prices." ], "metadata": { "id": "ePfWC4q44WBj" } }, { "cell_type": "code", "source": [ "# asking for customer's budget\n", "budget = int(input('Enter your budget(in dollars): '))\n", "\n", "# creating a list of Yes/No based on budget and discounted prices\n", "within_budget = ['Yes' if x <= budget else 'No' for x in discounted_price_list]\n", "print(within_budget)" ], "metadata": { "id": "Pg0Ws8qz36Ce", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ce7becf2-2ee2-4022-b627-523c1eb61569" }, "execution_count": 69, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Enter your budget(in dollars): 500\n", "['No', 'No', 'No', 'No']\n" ] } ] }, { "cell_type": "markdown", "source": [ "To get more clarity on the way the list comprehension syntax is formulated, we can expand the list comprehension to the usual for and if statements and think of this in a reversed way." ], "metadata": { "id": "lU5qWotf5EjH" } }, { "cell_type": "code", "source": [ "within_budget = []\n", "\n", "for x in discounted_price_list:\n", " if x <= budget:\n", " within_budget.append('Yes')\n", " else:\n", " within_budget.append('No')\n", "\n", "print(within_budget)" ], "metadata": { "id": "Q-bj32zx5h3z", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "a008b3ec-7264-41c7-dc41-c88875ce12e2" }, "execution_count": 70, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "['No', 'No', 'No', 'No']\n" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "xEPReYdxm-E5" }, "source": [ "## 1.6 Functions in Python" ] }, { "cell_type": "markdown", "metadata": { "id": "XsVOy7oaoSXM" }, "source": [ "**What is a Function in Python?**\n", "\n", "In Python, a function is a block of instructions that performs a specific task.\n", "\n", "We have already seen a few functions in python. min and max were functions that found the minimum and maximum numbers in a list!\n", "\n", "In Python, we can also define our own functions! We don't have to rely on the ones that are already there.\n", "\n", "Functions break the program into modular chunks which can be reused later. Functions are used to make the program more organized and manageable.\n", "\n", "\n", "**Syntax of a function**\n", "\n", "Functions that users define themselves to a particular task are referred to as user-defined functions.\n", "\n", "```\n", "def function_name(parameters):\n", "\t'''explain what a function does'''\n", "\tstatement(s)\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "kMUsQDMVpgHh" }, "source": [ "Let's say the store wants to market the Apple iPhone by displaying its attributes to each customer.\n", "\n", "Q. Write a function in Python that displays the attributes of the Apple iPhone." ] }, { "cell_type": "code", "metadata": { "id": "2qdL41zapfT5" }, "source": [ "# write the function\n", "def display_iphone_attributes():\n", " \"\"\"\n", " This function displays\n", " the stored attributes of\n", " the Apple iPhone\n", " \"\"\"\n", " # store the price (in dollars) of the mobile in variable 'price'\n", " price = 900\n", " # store the RAM (in GB) of the mobile in variable 'ram'.\n", " ram = 4\n", " # store the internal storage (in GB) of the mobile in variable 'storage'.\n", " storage = 128\n", " # display the details\n", " print('The Apple iPhone has ', ram, ' GB RAM and ', storage, ' GB internal storage and it costs $', price, sep='')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "8SQoJ4wWr-1g" }, "source": [ "**How to call a function in python?**\n", "\n", "Once the function is defined, we can simply call the function by writing the function name with appropriate parameters. The function definition must always be written before the function call. Else, we will get an error." ] }, { "cell_type": "code", "metadata": { "id": "qmSi4POvsYTM" }, "source": [ "# call the function\n", "display_iphone_attributes()" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "8bKo7D3JtjlK" }, "source": [ "**How to write a Python function with arguments?**\n", "\n", "In Python, you can also define a function that takes a variable number of arguments. Let's try an example!\n", "\n", "Q. Write a function in Python that displays the attributes of a phone.\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "do-AAwmitijp" }, "source": [ "# write the function\n", "def display_phone_attributes(brand, price, ram, storage):\n", " \"\"\"\n", " This function displays\n", " the stored attributes of\n", " any phone\n", " \"\"\"\n", " # display the details\n", " print('The ', brand, ' phone has ', ram, ' GB RAM and ', storage,' GB internal storage and it costs $',price,sep='')" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "YHqgx5GWwZGT" }, "source": [ "# call the function\n", "display_phone_attributes('samsung', 899, 12, 128)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "Dpqah3c3xcuO" }, "source": [ "Since we have called the function with the appropriate number of arguments, it runs smoothly without any error. The interpreter will show an error message in case we call it with a different number of arguments.\n", "\n", "Let's try calling the function with 3 arguments." ] }, { "cell_type": "code", "metadata": { "id": "sLwV4-39xzDA" }, "source": [ "# call the function with 3 arguments\n", "display_phone_attributes('samsung', 899, 12)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "es8xsN4dx8wG" }, "source": [ "**What is a return statement?**\n", "\n", "The return statement is used to exit a function and also returns the output.\n", "\n", "Q. Write a function in Python that takes the discount percentage as input and returns the discounted price of an Apple iPhone." ] }, { "cell_type": "code", "metadata": { "id": "gHOoGYQzyjYw" }, "source": [ "# write the function\n", "def dis_price(discount):\n", " \"\"\"\n", " This function takes the discount \n", " percentage as input and \n", " returns the discounted price of Apple iPhone\n", " \"\"\"\n", " # store the price (in dollars) of the mobile in variable 'price'\n", " price = 900\n", " # calculate the price after discount\n", " discounted_price = price - price * (discount / 100)\n", " # return the discounted price\n", " return discounted_price" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "kfxk0YnjzIdu" }, "source": [ "# call the function with discount = 10%\n", "dp = dis_price(10)\n", "dp" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "_IPo7Bjiz7T0" }, "source": [ "In Python, lambda function are functions a different way to define a function \n", "\n", "* User-defined functions are defined using the def keyword, whereas lambda functions are defined using the lambda keyword.\n", "* We generally use them when we require an anonymous function for a small task\n", "* We cannot use a return statement with lambda functions.\n", "\n", "Let's try to get the discounted price using lambda function." ] }, { "cell_type": "code", "metadata": { "id": "DggmBW-X0xxa" }, "source": [ "# lambda functions\n", "dis_price_lambda = lambda discount : 900 - ( 900 * (discount / 100) ) " ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "0ptZLkjR1ER6" }, "source": [ "# call the function with discount = 10%\n", "dis_price_lambda(10)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "source": [ "## 1.7 \\*args and \\**kwargs" ], "metadata": { "id": "JE2FLBCIejeA" } }, { "cell_type": "markdown", "source": [ "A customer has placed an order for 5 mobile phones with MobiWorld. The store wants to generate the total amount for the order.\n", "\n", "We can define a function with 5 arguments (one each for the price of the mobile phone ordered) to compute the total amount." ], "metadata": { "id": "DssVB5yJiDpe" } }, { "cell_type": "code", "source": [ "def total_amount(price1, price2, price3, price4, price5):\n", " \"\"\"\n", " This function takes the price of five phones ordered\n", " and returns the total order amount.\n", " \"\"\"\n", " # computing the total order amount\n", " total = price1 + price2 + price3 + price4 + price5\n", "\n", " # return the total amount\n", " return total" ], "metadata": { "id": "QWd7asLjivuh" }, "execution_count": 71, "outputs": [] }, { "cell_type": "code", "source": [ "print('Total order amount:', total_amount(700, 599, 650, 900, 820))" ], "metadata": { "id": "RujDjojrkGBk", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "b1706933-2c3e-4de9-d9c6-e5c6eb0f4a1d" }, "execution_count": 72, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Total order amount: 3669\n" ] } ] }, { "cell_type": "markdown", "source": [ "This works as we have a small number of items in the order placed. What if the customer decides to add 5 more phones to his order? It will become tedious to keep adding an argument to the function for each new addition.\n", "\n", "* In some cases, we might not even want any constraints on the number of arguments for the function." ], "metadata": { "id": "nswSW0-9k7gz" } }, { "cell_type": "markdown", "source": [ "**Python allows us flexibility in terms of the number of arguments passed to a function by using \\*args.**" ], "metadata": { "id": "yCj_GaLAgpLn" } }, { "cell_type": "code", "source": [ "def total_amount(*args):\n", " \"\"\"\n", " This function takes the prices of phones ordered\n", " and returns the total order amount.\n", " \"\"\"\n", " total = 0\n", " # computing the total order amount\n", " for arg in args:\n", " total += arg\n", "\n", " # return the total amount\n", " return total" ], "metadata": { "id": "Kp20hXTbel28" }, "execution_count": 73, "outputs": [] }, { "cell_type": "markdown", "source": [ "Let's compute the total amount for 5 phones." ], "metadata": { "id": "iotLTjjAnehn" } }, { "cell_type": "code", "source": [ "print('Total order amount:', total_amount(700, 599, 650, 900, 820))" ], "metadata": { "id": "QTkUyHYJnc0I", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "407ac174-7ed6-4d34-d72e-f1d63fbb4f4f" }, "execution_count": 74, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Total order amount: 3669\n" ] } ] }, { "cell_type": "markdown", "source": [ "Now, let's compute the total amount for 10 phones." ], "metadata": { "id": "FWyaI_WqnriO" } }, { "cell_type": "code", "source": [ "print('Total order amount:', total_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840))" ], "metadata": { "id": "2ZsZt-FLnxcp", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "0837e21a-84fd-47c8-c3a5-273e26f6a1c1" }, "execution_count": 75, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Total order amount: 7457\n" ] } ] }, { "cell_type": "markdown", "source": [ "We can also use any other text in place of *args*." ], "metadata": { "id": "DMovmVM2nHVR" } }, { "cell_type": "code", "source": [ "def total_amount(*prices):\n", " \"\"\"\n", " This function takes the prices of phones ordered\n", " and returns the total order amount.\n", " \"\"\"\n", " total = 0\n", " # computing the total order amount\n", " for price in prices:\n", " total += price\n", "\n", " # return the total amount\n", " return total" ], "metadata": { "id": "ylVGHrXfnHKR" }, "execution_count": 76, "outputs": [] }, { "cell_type": "code", "source": [ "print('Total order amount:', total_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840))" ], "metadata": { "id": "RKzMj2jrnHIC", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "fd480e47-fafa-4451-af18-95548b2a8435" }, "execution_count": 77, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Total order amount: 7457\n" ] } ] }, { "cell_type": "markdown", "source": [ "Till now, the arguments we have passed to our functions have been declared by names only, like brand, ram, price1. These types of arguments are called **positional arguments**.\n", "\n", "Another type of argument in Python is **called keyword argument**, which is declared using both a name and a default value." ], "metadata": { "id": "V3o5ByDooLFN" } }, { "cell_type": "markdown", "source": [ "Let us consider the festive season sale, where the store is offering a discount of 5% on all its products. Outside the sale period, there will be no discount for the products.\n", "\n", "Let's create a new function to compute the total discounted price for an order of one or more phones placed by a customer." ], "metadata": { "id": "tIDDR7GqpRzj" } }, { "cell_type": "code", "source": [ "def total_discounted_amount(*prices, discount=0.0):\n", " \"\"\"\n", " This function takes the prices of phones ordered\n", " and the discount percentage\n", " and returns the total discounted order amount.\n", " \"\"\"\n", " total = 0\n", " # computing the total order amount\n", " for price in prices:\n", " total += price\n", "\n", " total_discounted_price = total - discount*total\n", " \n", " # return the total amount\n", " return total_discounted_price" ], "metadata": { "id": "KwFVie38nHFl" }, "execution_count": 78, "outputs": [] }, { "cell_type": "code", "source": [ "print('Total discounted order amount:', total_discounted_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840))" ], "metadata": { "id": "eAoxq0-arNT-", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ac9cd419-6d38-41af-bb12-5c30d47da1ab" }, "execution_count": 79, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Total discounted order amount: 7457.0\n" ] } ] }, { "cell_type": "markdown", "source": [ "The discount percentage during the festive season sale will be 5%, which we can specify by setting the keyword argument *discount* to 0.05." ], "metadata": { "id": "e3fU3p0trmSz" } }, { "cell_type": "code", "source": [ "print('Total discounted order amount (during festive season):', total_discounted_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840, discount=0.05))" ], "metadata": { "id": "NY1oWOAWrNR2", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "af230853-2e86-4bab-bbf0-7b97d80c7bf6" }, "execution_count": 80, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Total discounted order amount (during festive season): 7084.15\n" ] } ] }, { "cell_type": "markdown", "source": [ "**Note**: In Python, keyword arguments should be declared after the positional arguments." ], "metadata": { "id": "cMvR2qXc-3ZH" } }, { "cell_type": "code", "source": [ "def total_discounted_amount(discount=0.0, *prices):\n", " \"\"\"\n", " This function takes the prices of phones ordered\n", " and the discount percentage\n", " and returns the total discounted order amount.\n", " \"\"\"\n", " total = 0\n", " # computing the total order amount\n", " for price in prices:\n", " total += price\n", "\n", " total_discounted_price = total - discount*total\n", " \n", " # return the total amount\n", " return total_discounted_price" ], "metadata": { "id": "P8jWyqxT-21L" }, "execution_count": 81, "outputs": [] }, { "cell_type": "code", "source": [ "print('Total discounted order amount (during festive season):', total_discounted_amount(discount=0.05, 700, 599, 650, 900, 820, 630, 520, 799, 999, 840))" ], "metadata": { "id": "cOGENuPH_Byi", "colab": { "base_uri": "https://localhost:8080/", "height": 149 }, "outputId": "1b14cf76-ea01-4d6c-e2cf-4e37d5043932" }, "execution_count": 82, "outputs": [ { "output_type": "error", "ename": "SyntaxError", "evalue": "ignored", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m print('Total discounted order amount (during festive season):', total_discounted_amount(discount=0.05, 700, 599, 650, 900, 820, 630, 520, 799, 999, 840))\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m positional argument follows keyword argument\n" ] } ] }, { "cell_type": "markdown", "source": [ "If we assign a value to a positional argument, it becomes a keyword argument. Since it is followed by positional arguments, we get a SyntaxError." ], "metadata": { "id": "9bfBORmP_B9Z" } }, { "cell_type": "markdown", "source": [ "Just like \\*args helped us remove the constraint on the number of positional arguments, \\**kwargs helps us remove the constraint on the number of keyword arguments.\n", "\n", "The \\**kwargs argument passed while calling the function must be a mapping, such as a dictionary." ], "metadata": { "id": "zy1c9pLdsC4I" } }, { "cell_type": "markdown", "source": [ "MobiWorld has decided to offer a \\$5 cashback on all the products on top of the 5% discount for the last day of the festive season sale. Let's create a function to compute the customer's net spend." ], "metadata": { "id": "V1GvvsqZszot" } }, { "cell_type": "code", "source": [ "def customer_net_spend(*prices, discount=0.0, **kwargs):\n", " \"\"\"\n", " This function takes the prices of phones ordered,\n", " the discount percentage, and any other cost additions/subtractions,\n", " and returns the customer's net spend on the order.\n", " \"\"\"\n", " total = 0\n", " # computing the total order amount\n", " for price in prices:\n", " total += price\n", "\n", " total_discounted_price = total - discount*total\n", "\n", " net_spend = total_discounted_price - kwargs['cashback']\n", " \n", " # return the total amount\n", " return net_spend" ], "metadata": { "id": "FXpSsvqErNM-" }, "execution_count": 83, "outputs": [] }, { "cell_type": "code", "source": [ "additionals = {'cashback': 5}\n", "print('Customer net spend (during last day of festive season):', customer_net_spend(700, 599, 650, discount=0.05, **additionals))" ], "metadata": { "id": "EIsAtDpxvu6K", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "ab4b1c23-6ab5-45f7-e5fd-85cc0b445e6f" }, "execution_count": 84, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Customer net spend (during last day of festive season): 1846.55\n" ] } ] }, { "cell_type": "markdown", "source": [ "MobiWorld plans to introduce a reward-point system based on the total order amount. Reward points will be given as per the following scheme:\n", "\n", "* Total Amount >= 2000: 100 Reward Points\n", "* Total Amount >= 5000: 200 Reward Points\n", "* Total Amount >= 10000: 300 Reward Points\n", "\n", "Let's define a function that will return the total amount, net spend, and rewards points earned for the order." ], "metadata": { "id": "N1JbP5cP_jCR" } }, { "cell_type": "code", "source": [ "def order_summary(*prices, **additionals):\n", " \"\"\"\n", " This function takes the prices of phones ordered\n", " and any other cost additions/subtractions,\n", " and returns the total amount, net spend,\n", " and rewards points earned for the order.\n", " \"\"\"\n", " total = 0\n", " # computing the total order amount\n", " for price in prices:\n", " total += price\n", "\n", " net_spend = total - additionals['discount']*total - additionals['cashback']\n", "\n", " if total >= 10000:\n", " reward_points = 300\n", " elif total >= 5000:\n", " reward_points = 200\n", " elif total >= 2000:\n", " reward_points = 100\n", " else:\n", " reward_points = 0\n", " \n", " # return the total amount\n", " return total, net_spend, reward_points" ], "metadata": { "id": "1ANWNzPLDMpW" }, "execution_count": 85, "outputs": [] }, { "cell_type": "code", "source": [ "additionals = {'discount':0.05, 'cashback': 5}\n", "ta, ns, rp = order_summary(700, 599, 750, **additionals)\n", "print('Customer Order Summary:\\n', '\\nTotal Amount:', ta, '\\nTotal Discounted Amount:', ns, '\\nReward Points Earned:', rp)" ], "metadata": { "id": "CttK_RKoDMlA", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "f65b27e5-e0b2-4ce6-ac4a-0e195399da5c" }, "execution_count": 86, "outputs": [ { "output_type": "stream", "name": "stdout", "text": [ "Customer Order Summary:\n", " \n", "Total Amount: 2049 \n", "Total Discounted Amount: 1941.55 \n", "Reward Points Earned: 100\n" ] } ] }, { "cell_type": "markdown", "source": [ "***" ], "metadata": { "id": "_NZ2bn_vy6vJ" } } ] }