{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "name": "python_basics", "provenance": [], "collapsed_sections": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "wAF73eQ969Xh", "colab_type": "text" }, "source": [ "#**Python Basics(Hindi)**" ] }, { "cell_type": "markdown", "metadata": { "id": "mmfLgTPvomRK", "colab_type": "text" }, "source": [ "## **Index**" ] }, { "cell_type": "markdown", "metadata": { "id": "wSNFGNZEouhT", "colab_type": "text" }, "source": [ "1. Hello world\n", "2. Variables\n", "3. Input/Output\n", "4. Performing calculations\n", "5. Casting\n", "6. If Elif Else\n", "7. Booleans\n", "8. Logical Statements\n", "9. Lists\n", "10. Slicing\n", "11. Identity and Membership operators\n", "12. Tuples\n", "13. While Loops\n", "14. For loops\n", "15. Dictionaries\n", "16. Functions\n", "17. User defined function\n", "\n", "Thank You" ] }, { "cell_type": "markdown", "metadata": { "id": "amQAagsJ7c_-", "colab_type": "text" }, "source": [ "**Ex1 - Starting of with the Hello World in python.**" ] }, { "cell_type": "markdown", "metadata": { "id": "_tmKKtIxGrCk", "colab_type": "text" }, "source": [ "remember \"#\" or hastag is used to comment a line i.e it wont effet your code." ] }, { "cell_type": "code", "metadata": { "id": "j6O9QtTI65PI", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "f7c2e16e-4707-4e91-a19e-f75c6ea9f4c0" }, "source": [ "print(\"hello, world\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "hello, world\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "4e2KW8Ro71OD", "colab_type": "text" }, "source": [ "**Ex-2 Variables**" ] }, { "cell_type": "markdown", "metadata": { "id": "pKGfptfp8NmJ", "colab_type": "text" }, "source": [ "Ex2.1 String(Alphabets/letter/words) Variables." ] }, { "cell_type": "code", "metadata": { "id": "3tPUBAOL7jgn", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "fda27d56-8c51-4c10-f2d9-8b7d29e14b8a" }, "source": [ "a = \"Hello, World\" # Using these inverted quotes is important\n", "print(a) \n", "print(a) # Don't use inverted quotes while printing a variable." ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Hello, World\n", "Hello, World\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "Skt8nGUt8alD", "colab_type": "text" }, "source": [ "Ex 2.2 Integer(numbers) Variable" ] }, { "cell_type": "code", "metadata": { "id": "g26tuUOm8E3B", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "d0383218-8c69-4d58-df4b-d81eeded7964" }, "source": [ "a = 10 # no need to use inverted quotes when declaring an integer\n", "print(a)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "10\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "P9Y2HToz8yLs", "colab_type": "text" }, "source": [ "Important tip:- in python python variables are mutable(changable) i.e their vales can be changed.\n", "For Ex:-" ] }, { "cell_type": "code", "metadata": { "id": "9CklzLo49fVQ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "ee8d3e21-37aa-49d9-d7f1-1d084ba04851" }, "source": [ "a = \"hello\"\n", "print(a)\n", "a = \"hi\"\n", "print(a)\n", "a = 10 # it doesn't matter which type of value you are asssigning\n", "print(a)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "hello\n", "hi\n", "10\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "Oid9YSc9oIeT", "colab_type": "text" }, "source": [ "Ex 2.3 Adding two strings. and two integers." ] }, { "cell_type": "markdown", "metadata": { "id": "7yoSOHxsoM0Y", "colab_type": "text" }, "source": [ "We use \"+\" to add to strings. and also to add to add two integers." ] }, { "cell_type": "markdown", "metadata": { "id": "qHczngyYpQFl", "colab_type": "text" }, "source": [ "Ex 2.3.1 Adding two strings" ] }, { "cell_type": "code", "metadata": { "id": "qUuNf98soL86", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "9d82d9b5-7f53-490c-f2b4-022e8cea746c" }, "source": [ "# adding two strings.\n", "a = \"Pranay\"\n", "b = \"Joshi\"\n", "c = a+b\n", "print(c)\n", "# two print it seprately just add a blank space after \"Pranay \" or before \" Joshi\"\n", "a = \"Pranay \"\n", "b = \"Joshi\"\n", "c = a+b\n", "print(c)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "PranayJoshi\n", "Pranay Joshi\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "MPT0HTEWpHjD", "colab_type": "text" }, "source": [ "Ex 2.3.2 Adding two Integers" ] }, { "cell_type": "code", "metadata": { "id": "qbfrQMa0qX9c", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "c495405f-ddb3-40fc-91cc-8427692123eb" }, "source": [ "a = 10\n", "b = 20\n", "c = a+b\n", "print(c)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "30\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "v4GTnLmepzQL", "colab_type": "text" }, "source": [ "We will talk on performing calculations further." ] }, { "cell_type": "markdown", "metadata": { "id": "A4oPZFJbpmnD", "colab_type": "text" }, "source": [ "Remember:- you can only add a strig with string or an integer with integer. \n", "\n", "You can not add a string with an integer" ] }, { "cell_type": "markdown", "metadata": { "id": "6Xx73hVl9919", "colab_type": "text" }, "source": [ "**Ex-3 Input/Output**" ] }, { "cell_type": "markdown", "metadata": { "id": "VN7N8gbl-JyV", "colab_type": "text" }, "source": [ "Ex 3.1:- Output" ] }, { "cell_type": "markdown", "metadata": { "id": "wQLX00LK-WIO", "colab_type": "text" }, "source": [ "You might only be familiar with **print** command which is used to print/display the output" ] }, { "cell_type": "markdown", "metadata": { "id": "ZIAlRa4--l7w", "colab_type": "text" }, "source": [ "Here i am giving you different commands you may use when printing." ] }, { "cell_type": "code", "metadata": { "id": "lgClGo6l99cR", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "e0faad92-08bf-401d-a5f6-d077fc183fb3" }, "source": [ "print(\"9 D was the best class\") # normal" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "9 D was the best class\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "_TX94q5qBsis", "colab_type": "text" }, "source": [ "Printing sentence with new line" ] }, { "cell_type": "code", "metadata": { "id": "tW-AYFEw_lsh", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "0d5ba804-e75d-47f7-b29f-db21775e3c69" }, "source": [ "# printing in new line\n", "# we use \\n inside the quotes while printing\n", "print(\"9 D was the \\nbest class.\")\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "9 D was the \n", "best class.\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "OeIt2VVBFAKu", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "4d540296-15aa-436d-e959-cbca1a710d7e" }, "source": [ "# priting with the variable\n", "a = \"9 D was the\"\n", "b = \"best class\"\n", "print(a+\"\\n\"+b) # Dont forget to use inverted quotes for \"\\n\" or newline and also don't use quotes for Variables" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "9 D was the\n", "best class\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "zFNunS4yEsag", "colab_type": "text" }, "source": [ "Printing sentence with a tab" ] }, { "cell_type": "code", "metadata": { "id": "aZAYc7MrEvyU", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "35966798-383f-4a0c-f4ce-c9e52b1c09f2" }, "source": [ "# like we use \"\\n\" for printing newline .\n", "# for printing tab we use \"\\t\".\n", "print(\"9 D was the \\tbest class.\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "9 D was the \tbest class.\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "cthGfoGxFw3S", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "a6c7f849-2e6d-43ff-fb64-8746a8c84dfb" }, "source": [ "# priting with the variable\n", "a = \"hello\"\n", "b = \"python\"\n", "print(a+\"\\t\"+b) " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "hello\tpython\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "LxpdkwfkFzu2", "colab_type": "text" }, "source": [ "Common Errors while performing this task " ] }, { "cell_type": "markdown", "metadata": { "id": "tyhMc2duF7AN", "colab_type": "text" }, "source": [ "adding an Integer/number in the following manner." ] }, { "cell_type": "code", "metadata": { "id": "0p6GIIduFzAf", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 199 }, "outputId": "057537ff-604f-4c51-b17e-0e619d170cf7" }, "source": [ "a = 10\n", "b = \"python\"\n", "print(a+\"\\t\"+b) # when you will add an integer to the string it will cause the following error." ], "execution_count": null, "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[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m10\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mb\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"python\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;34m\"\\t\"\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0mb\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# when you will add an integer to the string it will cause the following error.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "a86Kbr-VGStQ", "colab_type": "text" }, "source": [ "Solution:- convert integer to the string" ] }, { "cell_type": "markdown", "metadata": { "id": "sMsSKf51GaO7", "colab_type": "text" }, "source": [ "To convert a integer to string you may use \"str()\" function" ] }, { "cell_type": "code", "metadata": { "id": "0YRm-I1IGRop", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "8cf68ea7-c431-4b94-afa9-9cc6c864448c" }, "source": [ "a = 10\n", "a = str(a)\n", "b = \"python\"\n", "print(a+\"\\t\"+b)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "10\tpython\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "kdGmO1z9IcG6", "colab_type": "text" }, "source": [ "Important Tips- You can convert an integer to string but you can not convert a string to integer." ] }, { "cell_type": "markdown", "metadata": { "id": "oI1vK61rnuW3", "colab_type": "text" }, "source": [ "Printing a varible after the statement ends." ] }, { "cell_type": "markdown", "metadata": { "id": "uq2zXcsPn7ut", "colab_type": "text" }, "source": [ "for printing the value of the variables use comma after the inverted quotes and the enter your variable name." ] }, { "cell_type": "code", "metadata": { "id": "Fl5IGsx0ntZr", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "0dda05a7-da6b-4a1d-b7c3-b9c9f74ffcee" }, "source": [ "age = 10\n", "age2 = 12\n", "print(\"your age is\", age, age2)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "your age is 10 12\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "v59O2LX7rsiw", "colab_type": "text" }, "source": [ "a difficult example." ] }, { "cell_type": "code", "metadata": { "id": "93owaAGGreDK", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "2d38f87d-5ca1-41d5-a3fa-2b13ecd088cf" }, "source": [ "age = 10\n", "name = \"Pranay\"\n", "surname = \"Joshi\"\n", "print(\"your age is \", age)\n", "print(\"your name is \", name)\n", "print(\"your surname is \", surname)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "your age is 10\n", "your name is Pranay\n", "your surname is Joshi\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "7dDmXjidtC95", "colab_type": "text" }, "source": [ "Here we have to type print many times. \n", "\n", "To overcome this problem we can use \"f\" key word before inverted quotes when printing. And inside the quotes we write normal statements\n", "'" ] }, { "cell_type": "code", "metadata": { "id": "olBsHjAZUzzl", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "f68566c9-5e01-453f-c3eb-0b81e3b9e385" }, "source": [ "age = 10\n", "name = \"Pranay\"\n", "surname = \"Joshi\"\n", "print(f\"your age is {age}\\nyour name is {name}\\nyour surname is {surname}\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "your age is 10\n", "your name is Pranay\n", "your surname is Joshi\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "OkvSRvNCoIxs", "colab_type": "text" }, "source": [ "Printing many variables in one line or via one print statement." ] }, { "cell_type": "code", "metadata": { "id": "CXMurXX-oSJB", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "07b02b20-e357-4d0b-f105-7648d171e45a" }, "source": [ "x = \"hi\"\n", "y = 42\n", "z = 42.021 # the decimal integers in python are called floats we will talk about them more in ch 5 Casting\n", "print(x,y,z)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "hi 42 42.021\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "d0TaFNo3-7HS", "colab_type": "text" }, "source": [ "Ex 3.2 Input" ] }, { "cell_type": "markdown", "metadata": { "id": "w1k2r5H4_F3I", "colab_type": "text" }, "source": [ "In python we take input using input command. here are some examples." ] }, { "cell_type": "markdown", "metadata": { "id": "tFW2hEoE_Pgf", "colab_type": "text" }, "source": [ "Ex 3.2.1 String/Word input" ] }, { "cell_type": "code", "metadata": { "id": "7aolUtXF8xS6", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "36d074cf-10cc-4215-a928-84bd946c7496" }, "source": [ "a = input() # We take string \n", "print(a) # printing the value in the variable a" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Pranay Joshi\n", "Pranay Joshi\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "KD1wpghCHNq8", "colab_type": "text" }, "source": [ "You may use this this input method to take a string input i.e whenever you will give an integer value it will not show an error but will show an error when you will use the variable for calculations" ] }, { "cell_type": "markdown", "metadata": { "id": "0VO-oEHUHm3C", "colab_type": "text" }, "source": [ "For ex:-" ] }, { "cell_type": "code", "metadata": { "id": "0T16S0gTHpVy", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 199 }, "outputId": "87154e98-2ea1-40da-965c-264832219abc" }, "source": [ "a = input()\n", "print(a+10) # we will talk about calculations in the upcoming tutorials" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "10\n" ], "name": "stdout" }, { "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[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m(\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[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;31m# we will talk about calculations in the upcoming tutorials\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: must be str, not int" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "uVgiDnzfH1Lw", "colab_type": "text" }, "source": [ "To solve the following error we may use \"int(input())\" command" ] }, { "cell_type": "markdown", "metadata": { "id": "NM8BTKB7HFbu", "colab_type": "text" }, "source": [ "Ex 3.2.2 taking an integer input" ] }, { "cell_type": "code", "metadata": { "id": "sxZKjTvPHEdZ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "dec9daa7-d3f0-47db-a54f-01cdf8fadd27" }, "source": [ "a = int(input())\n", "print(a+10)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "10\n", "20\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "8tfzCepdIUoI", "colab_type": "text" }, "source": [ "Important Tips:- Remember if you use int(input()) for taking input.If the input you give is not an integer/number than it will give an error." ] }, { "cell_type": "markdown", "metadata": { "id": "U3lDWSBgI-v0", "colab_type": "text" }, "source": [ "For ex- i will input \"hello\"" ] }, { "cell_type": "code", "metadata": { "id": "rj3hwTjJHAyN", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 199 }, "outputId": "f9e264fa-827a-4d81-a2c3-5e40693092f7" }, "source": [ "a = int(input())\n", "print(a+10)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Hello\n" ], "name": "stdout" }, { "output_type": "error", "ename": "ValueError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\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[0ma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m10\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: 'Hello'" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "8iRXqppEJQrv", "colab_type": "text" }, "source": [ "Note:- Earlier I told you you can not convert a string into an integer." ] }, { "cell_type": "markdown", "metadata": { "id": "q6tcRxnzJbWd", "colab_type": "text" }, "source": [ "But actually you can convert a string to an integer by using \"int()\" function but the string should be a number." ] }, { "cell_type": "markdown", "metadata": { "id": "thZiLF27Jkh-", "colab_type": "text" }, "source": [ "For ex-" ] }, { "cell_type": "code", "metadata": { "id": "TR5jKWdNJQIf", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "32932f3d-fd35-4884-d5d0-588ae979101a" }, "source": [ "a = input()\n", "b = int(a)\n", "print(b+10) # adding 10 to b\n", "# I entered 14 and it showed the result" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "14\n", "24\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "0BdweCO8nO9b", "colab_type": "text" }, "source": [ "taking input after printing" ] }, { "cell_type": "code", "metadata": { "id": "jh1JZuKPnWBU", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "f048cf56-db4c-463b-ca71-730648ed14ce" }, "source": [ "print(\"What is your name?\")\n", "a = input()\n", "print(\"your name is\", a)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "What is your name?\n", "Pranay\n", "your name is Pranay\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "5SWYI9qNm8LT", "colab_type": "text" }, "source": [ "Ex 3.2.3 Taking input after printing a line." ] }, { "cell_type": "markdown", "metadata": { "id": "6Z99K9FLnFgL", "colab_type": "text" }, "source": [ "You can also take input after printing a line. by using quotes inside brackets of input()/ int(input()) and type the line you want to print." ] }, { "cell_type": "code", "metadata": { "id": "C1OV1Ofkq45w", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "865bf8e1-d51c-48c8-cf16-22569bbe45ce" }, "source": [ "a = input(\"enter your name: \")\n", "print(a)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "enter your name: pranay\n", "pranay\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "zWCpU7uomr7v", "colab_type": "text" }, "source": [ "Class Execise:- 1" ] }, { "cell_type": "code", "metadata": { "id": "uAVWZqY5mrQB", "colab_type": "code", "colab": {} }, "source": [ "name = input(\"Enter your name\")\n", "age = int(input(\"Enter your age\"))\n", "father = input(\"Enter your father's name\")\n", "f_age = int(input(\"Enter your father's age\"))\n", "mother = # Mother name\n", "m_age = int(input(\"\"))\n", "print(\"Your name is {}. Your father name is {}. Your mother name is: {}\".format(name, father, mother))\n", "age_str = str(age)\n", "f_age_str = str()\n", "m_age_str = str()\n", "print(\"your age{}. your father's age{}. Your mother's{}\")\n", "age_sum =\n", "print(\" The sum of your family ages is.\", age_sum)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "_43G78NQKL8i", "colab_type": "text" }, "source": [ "** Ex4:- Performing calculations**" ] }, { "cell_type": "markdown", "metadata": { "id": "P1agXz8aKTD7", "colab_type": "text" }, "source": [ "In python you can perform calculations with mathematical symbols.\n", "\n", "for addition +\n", "\n", "for multiplication *\n", "\n", "for subtraction -\n", "\n", "for division /\n", "\n", "for exponent **\n", "\n", "for remainder %\n" ] }, { "cell_type": "markdown", "metadata": { "id": "sDr6gCN8mUoc", "colab_type": "text" }, "source": [ "Ex 4.1 Addition" ] }, { "cell_type": "code", "metadata": { "id": "9xHRjx_8meV-", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "bac65b6f-6cb3-4a7c-f39f-180f77871df4" }, "source": [ "a = 10\n", "b = 60\n", "print(a+b)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "70\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "DSTLdknimfP6", "colab_type": "text" }, "source": [ "Ex 4.2 Subtraction" ] }, { "cell_type": "code", "metadata": { "id": "QHDiYdXvJEO5", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "8287a56f-97f3-4a53-ff2b-b645636a734b" }, "source": [ "a = 10\n", "b = 60\n", "print(a-b)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "-50\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "hAxeFdCmJ931", "colab_type": "text" }, "source": [ "Ex 4.3 Multiplication" ] }, { "cell_type": "code", "metadata": { "id": "JebZIuaiJ9Wa", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "4c14d5a1-accd-4026-d2e1-4b212c6d27a6" }, "source": [ "a = 10\n", "b = 60\n", "print(a*b)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "600\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "k9IsZXFxKDv3", "colab_type": "text" }, "source": [ "Ex 4.4 Division" ] }, { "cell_type": "code", "metadata": { "id": "GxlxiSIdKCh9", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "96a0863b-cd1c-40b0-cea5-e5fff635b28a" }, "source": [ "a = 10\n", "b = 60\n", "print(a/b)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "0.16666666666666666\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "YiWiLzz6KoOs", "colab_type": "text" }, "source": [ "Ex 4.5 Exponent" ] }, { "cell_type": "code", "metadata": { "id": "yLC2je-IKm6I", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "c640807b-5d79-4658-c26d-e4431523041b" }, "source": [ "# we use \"**\" double astricts for exponents.\n", "# for ex.\n", "a = 10\n", "b = 2\n", "print(a**b) # this will print a to the power b i.e 10 to the power 2" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "100\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "3IX016gfLqf2", "colab_type": "text" }, "source": [ "you can take out the square root or cube root by dividing 1 by \"b\" in the above cae" ] }, { "cell_type": "code", "metadata": { "id": "60ZpynhILn0B", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "81fca262-a371-4947-b68d-dc8db18b4e8d" }, "source": [ "a = 10\n", "b = 2\n", "print(a**(1/b)) " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "3.1622776601683795\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "MrDpQeE7MBgC", "colab_type": "text" }, "source": [ "Ex 4.6 Remainder " ] }, { "cell_type": "code", "metadata": { "id": "bwOHlXoZL9QK", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "63b67a29-cc25-4ca3-febe-141ce12b887a" }, "source": [ "a = 10\n", "b = 2\n", "print(a%b) # this will output the remainder when we divide 10 /2 which is 0" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "0\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "1sbC9m48MSXH", "colab_type": "text" }, "source": [ "Remember:- python uses BODMAS rule for the calculation" ] }, { "cell_type": "markdown", "metadata": { "id": "PyS08vvBm9Ik", "colab_type": "text" }, "source": [ "**Ex 5 Casting**" ] }, { "cell_type": "markdown", "metadata": { "id": "PNyvvqD9nWmz", "colab_type": "text" }, "source": [ "There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types." ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "LFIct_VGkL9T" }, "source": [ "* int() - constructs an integer number from an integer literal, a float literal (by rounding down to the previous whole number), or a string literal (providing the string represents a whole number)\n", "* float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)\n", "* str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals" ] }, { "cell_type": "markdown", "metadata": { "id": "hpb7ZQQ_nZ2n", "colab_type": "text" }, "source": [ "Casting in python is therefore done using constructor functions:" ] }, { "cell_type": "markdown", "metadata": { "id": "GD0vhIyGnk8P", "colab_type": "text" }, "source": [ "Ex 5.1 Integers" ] }, { "cell_type": "code", "metadata": { "id": "mKQ3EVdBneIc", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "98f0398e-2664-4923-a603-656092712c03" }, "source": [ "x = int(1) # x will be 1\n", "y = int(2.8) # y will be 2\n", "z = int(\"3\") # z will be 3\n", "print(x, y, z)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "1 2 3\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "aGho2sT5npr9", "colab_type": "text" }, "source": [ "Ex 5.2 Float" ] }, { "cell_type": "markdown", "metadata": { "id": "SsQRXF5cnvmB", "colab_type": "text" }, "source": [ "first let us talk about float.\n", "Float is nothing but decimal." ] }, { "cell_type": "code", "metadata": { "id": "eNH1JDWrnune", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "4c002be5-dcb7-4513-d77a-67a59db5cfcc" }, "source": [ "x = float(1) # x will be 1.0\n", "y = float(2.8) # y will be 2.8\n", "z = float(\"3\") # z will be 3.0\n", "w = float(\"4.2\") # w will be 4.2\n", "print(x, y, z, w)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "1.0 2.8 3.0 4.2\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "k7xCe0Pkn4Cr", "colab_type": "text" }, "source": [ "Ex 5.3 Strigs" ] }, { "cell_type": "code", "metadata": { "id": "B5-bLskDn3L8", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "3839ae1d-be7a-408c-b423-d88e1dfb4876" }, "source": [ "x = str(\"s1\") # x will be 's1'\n", "y = str(2) # y will be '2'\n", "z = str(3.0) # z will be '3.0'\n", "print(x, y, z)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "s1 2 3.0\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "H76LcFqDkkna", "colab_type": "text" }, "source": [ "**Ex 6 IF Elif Else**" ] }, { "cell_type": "markdown", "metadata": { "id": "MyYB1hmXe-lv", "colab_type": "text" }, "source": [ "They are also known as Conditional statements" ] }, { "cell_type": "markdown", "metadata": { "colab_type": "text", "id": "27piRmF0kDkL" }, "source": [ "If elif and else, they are widely used commands in python or even in any programming language. They are pritty easy to understand but are very crucial part of programming. " ] }, { "cell_type": "markdown", "metadata": { "id": "2giDrFDXfU0V", "colab_type": "text" }, "source": [ "Signs:-\n", "* Equals: a == b\n", "* Not Equals: a != b\n", "* Less than: a < b\n", "* Less than or equal to: a <= b\n", "* Greater than: a > b\n", "* Greater than or equal to: a >= b" ] }, { "cell_type": "markdown", "metadata": { "id": "cAVlJUcjgIHh", "colab_type": "text" }, "source": [ "Ex 6.1 if statement" ] }, { "cell_type": "markdown", "metadata": { "id": "FjiG1M9Rf1iA", "colab_type": "text" }, "source": [ "An \"if statement\" is written by using the if keyword" ] }, { "cell_type": "code", "metadata": { "id": "P-nsbdkkMJ33", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "2977b10e-ea79-46f5-82f1-e4a1ee5a18d9" }, "source": [ "a = 33\n", "b = 10\n", "if b > a:\n", " print(\"b is greater than a\")\n", "print(a+b)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "43\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "3UkW6WWSf9b2", "colab_type": "text" }, "source": [ "In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that \"b is greater than a\"." ] }, { "cell_type": "markdown", "metadata": { "id": "B0IIjB6TgNBs", "colab_type": "text" }, "source": [ "Ex 6.2 Elif statement" ] }, { "cell_type": "markdown", "metadata": { "id": "vogcv-5hgTgs", "colab_type": "text" }, "source": [ "The elif keyword is pythons way of saying \"if the previous conditions were not true, then try this condition\"." ] }, { "cell_type": "code", "metadata": { "id": "SaILHERsfT7k", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "230d1661-40d8-46b6-ea30-eb0282b221e4" }, "source": [ "a = 33\n", "b = 33\n", "if b > a:\n", " print(\"b is greater than a\")\n", "elif a == b:\n", " print(\"a and b are equal\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "a and b are equal\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "K25Z_PpWgZF2", "colab_type": "text" }, "source": [ "In this example a is equal to b, so the first condition is not true, but the elif condition is true, so we print to screen that \"a and b are equal\"." ] }, { "cell_type": "markdown", "metadata": { "id": "9jFpE6qYggmz", "colab_type": "text" }, "source": [ "Ex 6.3 Else Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "3Aep6N9fggKT", "colab_type": "text" }, "source": [ "The else keyword catches anything which isn't caught by the preceding conditions" ] }, { "cell_type": "code", "metadata": { "id": "QUDEW2zngknQ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "0fb8ecdd-055d-4184-d008-0dee4ada39fd" }, "source": [ "a = int(input())\n", "b = int(input())\n", "if b > a:\n", " print(\"b is greater than a\")\n", "elif a == b:\n", " print(\"a and b are equal\")\n", "else:\n", " print(\"a is greater than b\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "23\n", "54\n", "b is greater than a\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "G5KU79TDgn63", "colab_type": "text" }, "source": [ "In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that \"a is greater than b\".\n", "\n", "You can also have an else without the elif:" ] }, { "cell_type": "markdown", "metadata": { "id": "xzS6H6gEgvrM", "colab_type": "text" }, "source": [ "For Example/" ] }, { "cell_type": "code", "metadata": { "id": "gqEja9cNgnMd", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "a6c5afb5-0467-4204-b158-f0b40d92444d" }, "source": [ "a = 200\n", "b = 33\n", "if b > a:\n", " print(\"b is greater than a\")\n", "else:\n", " print(\"b is not greater than a\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "b is not greater than a\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "v682Fu5okCvu", "colab_type": "text" }, "source": [ "Ex 6.4 Nested if's." ] }, { "cell_type": "markdown", "metadata": { "id": "G8Sgj7fOkJBu", "colab_type": "text" }, "source": [ "You can have if statements inside if statements, this is called nested if statements" ] }, { "cell_type": "code", "metadata": { "id": "Q4ZTRmwKkGs_", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "880c1a40-2c30-4b1a-9577-e80a11f68dde" }, "source": [ "x = 41\n", "if x > 10\n", " if x < 50:\n", " print(\"Above ten,\")\n", " print(\"and also above 20!\")\n", " else:\n", " print(\"but not above 20.\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Above ten,\n", "and also above 20!\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "zsYeRl5dYm8M", "colab_type": "text" }, "source": [ "**Ex 7 Boolean**" ] }, { "cell_type": "markdown", "metadata": { "id": "etwoZ4M1ZCdM", "colab_type": "text" }, "source": [ "In programming you often need to know if an expression is True or False.\n", "\n", "You can evaluate any expression in Python, and get one of two answers, True or False.\n", "\n", "When you compare two values, the expression is evaluated and Python returns the Boolean answer:" ] }, { "cell_type": "code", "metadata": { "id": "TSd30Sp_Yml3", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "b9c46bb0-8b2c-46f6-f1db-52592c0ac16e" }, "source": [ "print(10 > 9)\n", "print(10 == 9)\n", "print(10 < 9)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "True\n", "False\n", "False\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "hJWHKVDpZ8w0", "colab_type": "text" }, "source": [ "The bool() function allows you to evaluate any value, and give you True or False in return,\n", "\n", "Evaluate a string and a number:" ] }, { "cell_type": "code", "metadata": { "id": "fwBjS9r2apBV", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "463412a6-8a4a-4bb7-805d-4f50873eb789" }, "source": [ "print(bool(\"Hello\"))\n", "print(bool(10))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "True\n", "True\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "VRvVDxGBatLU", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "6fe21858-47c8-4900-9feb-74d712d8def1" }, "source": [ "x = \"Hello\"\n", "y = 15\n", "\n", "print(bool(x))\n", "print(bool(y))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "True\n", "True\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "BQr_l5N4j1YV", "colab_type": "text" }, "source": [ "**Ex 8 Logical Operators**" ] }, { "cell_type": "markdown", "metadata": { "id": "lA_uExrmkLyQ", "colab_type": "text" }, "source": [ "The Logical operators acts as a filter in the conditional statements" ] }, { "cell_type": "markdown", "metadata": { "id": "aXaFFdRgkXFQ", "colab_type": "text" }, "source": [ "These include\n", "* And\n", "* Or\n", "* not" ] }, { "cell_type": "markdown", "metadata": { "id": "7_NsbFma_hsS", "colab_type": "text" }, "source": [ "and\tLogical AND: True if both the operands are true.\n", "\n", "or\tLogical OR: True if either of the operands is true.\n", "\n", "not\tLogical NOT: True if operand is false." ] }, { "cell_type": "markdown", "metadata": { "id": "FFi2OAK1Cxv1", "colab_type": "text" }, "source": [ "Ex 8.1 And" ] }, { "cell_type": "markdown", "metadata": { "id": "5itlGFFw_o1p", "colab_type": "text" }, "source": [ "And Logical operator returns True if both the operands are True else it returns False." ] }, { "cell_type": "code", "metadata": { "id": "pBaxnn6vAbCp", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "4b48e9a3-3152-4288-dcac-819bec592e1c" }, "source": [ "a = 10\n", "b = 10\n", "c = -10\n", " \n", "if a > 0 and b > 0: \n", " print(\"The numbers are greater than 0\") \n", "if a > 0 and b > 0 and c > 0: \n", " print(\"The numbers are greater than 0\") \n", "else:\n", " print(\"Atleast one number is not greater than 0\") " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "The numbers are greater than 0\n", "Atleast one number is not greater than 0\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "ltvtTsUTBdhG", "colab_type": "text" }, "source": [ "Another example" ] }, { "cell_type": "code", "metadata": { "id": "StqnQ0IQBDE5", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "82154692-ce11-4412-9976-5253c792c590" }, "source": [ "a = 10\n", "b = 12\n", "c = 0\n", " \n", "if a and b and c: \n", " print(\"All the numbers have boolean value as True\") \n", "else: \n", " print(\"Atleast one number has boolean value as False\") " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Atleast one number has boolean value as False\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "bcGsdQXvCpvm", "colab_type": "text" }, "source": [ "Ex 8.2 Or" ] }, { "cell_type": "markdown", "metadata": { "id": "ci18lsIYBgxU", "colab_type": "text" }, "source": [ "Or Logical operator returns True if either of the operands is True." ] }, { "cell_type": "code", "metadata": { "id": "-GxpeHEdBn5u", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 51 }, "outputId": "433774c4-edb3-4394-af9a-7c5b31c2de71" }, "source": [ "a = 10\n", "b = -10\n", "c = 0\n", " \n", "if a > 0 or b > 0: \n", " print(\"Either of the number is greater than 0\") \n", "else: \n", " print(\"No number is greater than 0\") \n", " \n", "if b > 0 or c > 0: \n", " print(\"Either of the number is greater than 0\") \n", "else: \n", " print(\"No number is greater than 0\") " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Either of the number is greater than 0\n", "No number is greater than 0\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "vBltCUfmCc52", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "58d75da0-7b5f-413d-fe6a-7f297230e833" }, "source": [ "a = 10\n", "b = 12\n", "c = 0\n", " \n", "if a or b or c: \n", " print(\"Atleast one number has boolean value as True\") \n", "else: \n", " print(\"All the numbers have boolean value as False\") " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Atleast one number has boolean value as True\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "kf0rLosWCmex", "colab_type": "text" }, "source": [ "Ex 8.3 Not" ] }, { "cell_type": "markdown", "metadata": { "id": "g1Fmjs7aCiSB", "colab_type": "text" }, "source": [ "Not Logical operator work with the single boolean value. If the boolean value is True it returns False and vice-versa." ] }, { "cell_type": "code", "metadata": { "id": "dEo31cBbC4bT", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "90d893f3-e5a3-478a-f3f4-37e960332d98" }, "source": [ "a = 10\n", "if not a>12: \n", " print(\"Boolean value of a is True\") \n", "if not (a%3 == 0 or a%5 == 0): \n", " print(\"10 is not divisible by either 3 or 5\") \n", "else: \n", " print(\"10 is divisible by either 3 or 5\") " ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Boolean value of a is True\n", "10 is divisible by either 3 or 5\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "-etkMmtCC7xz", "colab_type": "text" }, "source": [ "**Ex 9 Lists**" ] }, { "cell_type": "markdown", "metadata": { "id": "iChRqqtcq0rK", "colab_type": "text" }, "source": [ "There are 3 collection data types in the Python programming language:\n", "\n", "* List is a collection which is ordered and changeable. Allows duplicate members.\n", "* Tuple is a collection which is ordered and unchangeable. Allows duplicate members.\n", "* Dictionary is a collection which is unordered, changeable and indexed. No duplicate members." ] }, { "cell_type": "markdown", "metadata": { "id": "vBhyLPraq73W", "colab_type": "text" }, "source": [ "A list is a collection which is ordered and changeable. In Python lists are written with square brackets." ] }, { "cell_type": "markdown", "metadata": { "id": "J5UeyKmqrC-Q", "colab_type": "text" }, "source": [ "Ex 9.1 Creating a list" ] }, { "cell_type": "code", "metadata": { "id": "1RO6MJkPC7Zh", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "ee872c6a-9e4a-4ef5-df6c-518b1deb3c3a" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\", 20, 40]\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'banana', 'cherry', 20]\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "FFt5jvlJrNMr", "colab_type": "text" }, "source": [ "Ex 9.2 Accessing elements" ] }, { "cell_type": "markdown", "metadata": { "id": "kZQGOFterYEf", "colab_type": "text" }, "source": [ "You access the list items by referring to the index number:" ] }, { "cell_type": "code", "metadata": { "id": "wkMVFWBrrdit", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "b465de3a-a93e-4f10-c915-77de6b930731" }, "source": [ "lst = [\"apple\", \"banana\", \"cherry\"]\n", "print(lst[0]) # here zero is the index\n", "print(lst[1]) # here 1 is the index\n", "print(lst[2]) # here 2 is the index" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "apple\n", "banana\n", "cherry\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "yRgwNyNErvAt", "colab_type": "text" }, "source": [ "Important note:- In aevery programming language counting starts from 0 not 1. YOu may see the above example." ] }, { "cell_type": "markdown", "metadata": { "id": "uNkyldkXsJYA", "colab_type": "text" }, "source": [ "Ex 9.3 Error" ] }, { "cell_type": "markdown", "metadata": { "id": "fz_eizUssQtB", "colab_type": "text" }, "source": [ "Whenever you will try to access an element which is out of index it will give you an error like \n", "\n", " list index out of range\n", "\n", "For ex." ] }, { "cell_type": "code", "metadata": { "id": "dZntC0pzscM3", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "52e1be7c-7ba1-429a-88cc-5bbcc1f6805e" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "print(thislist[1])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "banana\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "ljW4HW9cufYQ", "colab_type": "text" }, "source": [ "Ex 9.4 Negative Indexing" ] }, { "cell_type": "markdown", "metadata": { "id": "kkBYC5x9ujtx", "colab_type": "text" }, "source": [ "Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc." ] }, { "cell_type": "code", "metadata": { "id": "06CiM8v2ume2", "colab_type": "code", "colab": {} }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "print(thislist[-1])" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "3xXL0OW23KQn", "colab_type": "text" }, "source": [ "Ex 9.5 Adding Items" ] }, { "cell_type": "markdown", "metadata": { "id": "67R0Ui1b5ROd", "colab_type": "text" }, "source": [ "Ex 9.5.1 Appending Method" ] }, { "cell_type": "markdown", "metadata": { "id": "E4ViGwmq3twS", "colab_type": "text" }, "source": [ "You can simply add an item using append() command. For ex." ] }, { "cell_type": "code", "metadata": { "id": "b6KcWTNa3195", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "9fb725a3-1e98-41f3-9fae-054498e7b1ab" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "thislist.append(\"orange\")\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'banana', 'cherry', 'orange']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "yI5BQlSFEZfm", "colab_type": "text" }, "source": [ "Ex 9.5.2 Inserting method" ] }, { "cell_type": "markdown", "metadata": { "id": "0Y7tFrEM4cnD", "colab_type": "text" }, "source": [ "To add an item at the specified index, use the insert() method:" ] }, { "cell_type": "markdown", "metadata": { "id": "sdUEIerJ4gEv", "colab_type": "text" }, "source": [ "Insert an item as the second position" ] }, { "cell_type": "code", "metadata": { "id": "gJGh7MRW4dbC", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "35e893a4-051b-41c7-84f7-9680fb7fe1b1" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "thislist.insert(1, \"orange\")\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'orange', 'banana', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "pSWd54b234Jm", "colab_type": "text" }, "source": [ "Ex 9.6 Removing Elements" ] }, { "cell_type": "markdown", "metadata": { "id": "grpHTAR_5Xtu", "colab_type": "text" }, "source": [ "Ex 9.6.1 Remove method" ] }, { "cell_type": "markdown", "metadata": { "id": "TBALJx_g3_0K", "colab_type": "text" }, "source": [ "You can simply remove an item using remove() command. For ex." ] }, { "cell_type": "code", "metadata": { "id": "_P3en2fO4Cwl", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "1baea76b-4372-4031-a7ba-a824e8fda938" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "thislist.remove(\"banana\")\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "aw32OD7F5cLh", "colab_type": "text" }, "source": [ "Ex 9.6.2 Pop method" ] }, { "cell_type": "markdown", "metadata": { "id": "6XcLlQQt5fMH", "colab_type": "text" }, "source": [ "The pop() method removes the specified index, (or the last item if index is not specified):" ] }, { "cell_type": "code", "metadata": { "id": "fdLAyeox5iQr", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "f14eb03a-1de1-49e0-8ba6-2ec8ccf35e0a" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "thislist.pop(1)\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "BRUxRXGe5koq", "colab_type": "text" }, "source": [ "Ex 9.6.3 Del Method" ] }, { "cell_type": "markdown", "metadata": { "id": "Aa89Bl885qoJ", "colab_type": "text" }, "source": [ "The del keyword removes the specified index:" ] }, { "cell_type": "code", "metadata": { "id": "NScaqC3A5onX", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "78324686-b082-49d3-ac00-27d7a57e8bdb" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "del thislist[0]\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['banana', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "9vsJ4SVt5530", "colab_type": "text" }, "source": [ "Ex 9.6.4 Clear Method" ] }, { "cell_type": "markdown", "metadata": { "id": "sUPVkONu588o", "colab_type": "text" }, "source": [ "The clear() method empties the list:" ] }, { "cell_type": "code", "metadata": { "id": "wqQYkajE5-f-", "colab_type": "code", "colab": {} }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "thislist.clear()\n", "print(thislist)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "XZKVrZez6Ab-", "colab_type": "text" }, "source": [ "Ex 9.7 copying a list" ] }, { "cell_type": "markdown", "metadata": { "id": "kguVthka6HsK", "colab_type": "text" }, "source": [ "Ex 9.7.1 normal method" ] }, { "cell_type": "markdown", "metadata": { "id": "7xAQg0ZF6LTR", "colab_type": "text" }, "source": [ "You can simply use the method of copying a variable. For ex." ] }, { "cell_type": "code", "metadata": { "id": "qo0yYEwb6Ra1", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "511b6007-2d0c-4e0b-b53b-c3525c9dfeab" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "mylist = thislist\n", "print(mylist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'banana', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "yxdoAoi46RHS", "colab_type": "text" }, "source": [ "Ex 9.7.2 Copy() Method" ] }, { "cell_type": "code", "metadata": { "id": "plvocgOz6HYN", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "a8e2b3a6-81a4-42eb-fb9b-d6e8f62ec9a7" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "mylist = thislist.copy()\n", "print(mylist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'banana', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "9QXhxjgm6dAS", "colab_type": "text" }, "source": [ "Ex 9.8 Joining two Lists." ] }, { "cell_type": "markdown", "metadata": { "id": "ntpSxPiZ6kp8", "colab_type": "text" }, "source": [ "Ex 9.8.1 Normal/Standard way" ] }, { "cell_type": "code", "metadata": { "id": "ZvHby4OM6gVT", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "2587642b-d7a3-4501-ee7f-729800b60a67" }, "source": [ "list1 = [\"a\", \"b\" , \"c\"]\n", "list2 = [1, 2, 3]\n", "\n", "list3 = list2 + list1\n", "print(list3)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "[1, 2, 3, 'a', 'b', 'c']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "cuJoiXU_6hUB", "colab_type": "text" }, "source": [ "Ex 9.8.2 Extend() Method" ] }, { "cell_type": "markdown", "metadata": { "id": "Q1rOTB686sAa", "colab_type": "text" }, "source": [ "Use the extend() method to add list2 at the end of list1:" ] }, { "cell_type": "code", "metadata": { "id": "28XaoE8Q6thR", "colab_type": "code", "colab": {} }, "source": [ "list1 = [\"a\", \"b\" , \"c\"]\n", "list2 = [1, 2, 3]\n", "\n", "list1.extend(list2)\n", "print(list1)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "noPpT7Ms6wD0", "colab_type": "text" }, "source": [ "Ex 9.9 The list() Constructor" ] }, { "cell_type": "markdown", "metadata": { "id": "YcFSx2MZ61eZ", "colab_type": "text" }, "source": [ "Here is the example of a list conductor" ] }, { "cell_type": "code", "metadata": { "id": "pYPN9T4p65ie", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "ddae4ae1-d168-47b3-ea71-00402975b536" }, "source": [ "thislist = list((\"apple\", \"banana\", \"cherry\")) # note the double round-brackets\n", "print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'banana', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "VBf0gSAL61Ss", "colab_type": "text" }, "source": [ "Here is another example. If you want to convert every letter of a string into a list element" ] }, { "cell_type": "code", "metadata": { "id": "gpW7fjfs7OPu", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 55 }, "outputId": "2b5311bd-5ff6-43ec-ff63-54fd76b9c79c" }, "source": [ "a = list(\"abcdefghijklmnopqrstuvwxyz\")\n", "print(a)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "HDFe1KEv7i_I", "colab_type": "text" }, "source": [ "Ex 9.10 sets" ] }, { "cell_type": "markdown", "metadata": { "id": "1JyYyW8u7rg0", "colab_type": "text" }, "source": [ "Set is also known as the fourth type of array but it's used rarely. We will use it here as a helper to the list" ] }, { "cell_type": "markdown", "metadata": { "id": "XWwAkzq48HW-", "colab_type": "text" }, "source": [ "Ex 9.10.1 Using set() to remove the multiple occurance of an element in the list." ] }, { "cell_type": "code", "metadata": { "id": "ek8Ohlhk7pYG", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "2b99a27e-e69d-4076-8e79-91653bbc8354" }, "source": [ "a = [\"apple\", \"banana\", \"cherry\",\"apple\", \"banana\"]\n", "a = set(a)\n", "print(list(a))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['cherry', 'banana', 'apple']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "fs4cUpmwcMgg", "colab_type": "text" }, "source": [ "Ex 9.11 Reversing the list." ] }, { "cell_type": "code", "metadata": { "id": "cGm2AQ1xcL5o", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "a267a650-05f9-49c7-a6e0-c404d3f336c8" }, "source": [ "fruits = ['apple', 'banana', 'cherry']\n", "\n", "fruits.reverse()\n", "print(fruits)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['cherry', 'banana', 'apple']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "nNAtDthvd6v-", "colab_type": "text" }, "source": [ "Ex 9.12 Sort" ] }, { "cell_type": "markdown", "metadata": { "id": "Ljz9DuaQeF7L", "colab_type": "text" }, "source": [ "Ex 9.12.1 Sorting the list (asscending)" ] }, { "cell_type": "markdown", "metadata": { "id": "HRUlA7ZkeWKy", "colab_type": "text" }, "source": [ "The sort() method sorts the list ascending by default." ] }, { "cell_type": "code", "metadata": { "id": "6p4Amb6leMAF", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "0c57924a-5d3e-49eb-b54a-fdbc81c29ec2" }, "source": [ "cars = ['Ford', 'BMW', 'Volvo']\n", "\n", "cars.sort()\n", "print(cars)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['BMW', 'Ford', 'Volvo']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "lc6WSUJHfPdz", "colab_type": "text" }, "source": [ "when list contains an integer values" ] }, { "cell_type": "code", "metadata": { "id": "rt5OUXjpfPBJ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "464b5ef5-8fe2-4f28-c16e-b28e48419e8b" }, "source": [ "no = [2,1,5,4,3]\n", "no.sort()\n", "print(no)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "[1, 2, 3, 4, 5]\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "B3u8hgCPeXU3", "colab_type": "text" }, "source": [ "Ex 9.12.2 Sorting the list(descending)" ] }, { "cell_type": "markdown", "metadata": { "id": "eESHZnfvegFW", "colab_type": "text" }, "source": [ "You can also make a function to decide the sorting criteria(s). For ex :-" ] }, { "cell_type": "code", "metadata": { "id": "gEbyuFvVekg7", "colab_type": "code", "colab": {} }, "source": [ "cars = ['Ford', 'BMW', 'Volvo']\n", "cars.sort(reverse=True)\n", "print(cars)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "BDCljB9tfhL7", "colab_type": "text" }, "source": [ "With integer values." ] }, { "cell_type": "code", "metadata": { "id": "LjGQW6GbfjX7", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "cbc4abda-b567-4d75-8a0a-57cb01d2e3f6" }, "source": [ "no = [2,1,5,4,3]\n", "\n", "no.sort(reverse=True)\n", "print(no)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "[5, 4, 3, 2, 1]\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "7UfiHu3se-k0", "colab_type": "text" }, "source": [ "Ex 9.13 Count" ] }, { "cell_type": "markdown", "metadata": { "id": "5RP0MsGrfCim", "colab_type": "text" }, "source": [ "The count() method returns the number of elements with the specified value." ] }, { "cell_type": "code", "metadata": { "id": "6ndGjhkafGfh", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "82d73c5c-7870-4e3f-ec49-e3d3af1db8e4" }, "source": [ "points = [1, 4, 2, 9, 7, 8, 9, 3, 1]\n", "x = points.count(9)\n", "print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "2\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "mWRALm3M-VV9", "colab_type": "text" }, "source": [ "**Ex 9.14 List index**" ] }, { "cell_type": "code", "metadata": { "id": "KXJueSpq-eJO", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "ddde0488-b9b6-4fdf-bad3-d10471b5d049" }, "source": [ "cars = ['Ford', 'BMW', 'Volvo']\n", "x = cars.index(\"Ford\")\n", "print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "0\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "gzZeGk7g_LXP", "colab_type": "text" }, "source": [ "**Ex 9.15 Len**" ] }, { "cell_type": "code", "metadata": { "id": "ZhsuYuBO_QHW", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "090171dc-aca9-486d-abb7-b617e795feae" }, "source": [ "cars = ['Ford', 'BMW', 'Volvo']\n", "x = len(cars)\n", "print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "3\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "ShyaEb9X3FFQ", "colab_type": "text" }, "source": [ "**Ex 10. Slicing**" ] }, { "cell_type": "markdown", "metadata": { "id": "EHG-5SgjAZCb", "colab_type": "text" }, "source": [ "The slicing returns a slice object that can use used to slice strings, lists, tuple etc." ] }, { "cell_type": "markdown", "metadata": { "id": "kYGZyXT-_29U", "colab_type": "text" }, "source": [ "Here is the syntax for slicing the list.\n", "\n", "\n", "```\n", "obj[start:stop:step]\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Rs5Gw28TBOdn", "colab_type": "text" }, "source": [ "Ex 10.1 Slicing Strings" ] }, { "cell_type": "code", "metadata": { "id": "kJE4M0lh_5Lv", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "e3f64a8f-6cb9-45b0-bf12-e9614a4ac05a" }, "source": [ "py_string = \"Python\"\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_string[2:])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Python\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "TpAhZ69E_2mi", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "588150dc-bf84-42d2-b50c-e6f7cdc2d390" }, "source": [ "py_string = 'Python'\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_string[0:5:2])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Pto\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "A5xhNcU0s2Hl", "colab_type": "text" }, "source": [ "Ex 10.2 Slicing Lists" ] }, { "cell_type": "code", "metadata": { "id": "tlhFlnBctNlg", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "d39997e2-ce2a-49aa-fd83-5e15f5426ee9" }, "source": [ "py_lst = [\"P\",\"y\",\"t\",\"h\",\"o\",\"n\"]\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_lst[0:3])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['P', 'y', 't']\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "nR4ogjtmtjn7", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "3ce9306b-8370-4f52-cd2a-25e75aa99b56" }, "source": [ "py_lst = [\"P\",\"y\",\"t\",\"o\",\"n\"]\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_lst[0:4:2])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['P', 't']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "OpDEn0pZt1d7", "colab_type": "text" }, "source": [ "Using the list() command" ] }, { "cell_type": "code", "metadata": { "id": "6OZTS1hAtzDc", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "1966fcb8-954b-46b0-d401-d0384743b061" }, "source": [ "py_lst = list(\"python\")\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_lst[0:5:2])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['p', 't', 'o']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "9SDD8Ilat9vZ", "colab_type": "text" }, "source": [ "Ex 10.3 Reversing th list and strings" ] }, { "cell_type": "markdown", "metadata": { "id": "II_Z287Vufwv", "colab_type": "text" }, "source": [ "Ex 10.3.1 Reversing a List" ] }, { "cell_type": "code", "metadata": { "id": "KIlRXb4LuFAD", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "a1f0f837-92eb-41e3-8e1b-067a06ef8043" }, "source": [ "py_lst = [\"P\",\"y\",\"t\",\"h\",\"o\",\"n\"]\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_lst[::-2])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['n', 'h', 'y']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "S1XaNqPBuKeo", "colab_type": "text" }, "source": [ "Ex 10.3.2 Reversing a string." ] }, { "cell_type": "code", "metadata": { "id": "SwcrNMosuPJE", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "a4b58c1e-8456-488f-802a-a30de35f0e7f" }, "source": [ "py_string = \"Python\"\n", "\n", "# contains indices 0, 1 and 2\n", "print(py_string[::-1])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "nohtyP\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "AxmOGuifk4Fc", "colab_type": "text" }, "source": [ "**Ex 11 Identity Operators**" ] }, { "cell_type": "markdown", "metadata": { "id": "N81EGBoKlMUi", "colab_type": "text" }, "source": [ "These includes-\n", "* in\n", "* not in\n", "* is\n", "* is not" ] }, { "cell_type": "markdown", "metadata": { "id": "PeqBFaZolL-M", "colab_type": "text" }, "source": [ "Ex 11.1 in Operator." ] }, { "cell_type": "markdown", "metadata": { "id": "b2xfFKbz3WJB", "colab_type": "text" }, "source": [ "In can be used in the following way." ] }, { "cell_type": "code", "metadata": { "id": "ZAaCoR0MlHje", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "ba4a31dd-2c20-42ce-ccc8-56e13d6c736b" }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "a = \"apple\"\n", "if a in thislist:\n", " thislist.append(\"apple2\")\n", " print(thislist)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'banana', 'cherry', 'apple2']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "DGmlYMAJ3dWk", "colab_type": "text" }, "source": [ "Ex 11.2 Not in" ] }, { "cell_type": "markdown", "metadata": { "id": "DHrsiJoa3hSc", "colab_type": "text" }, "source": [ "It act as opposite to in" ] }, { "cell_type": "code", "metadata": { "id": "kW2Ggoa5kK2r", "colab_type": "code", "colab": {} }, "source": [ "thislist = [\"apple\", \"banana\", \"cherry\"]\n", "if \"apple\" not in thislist:\n", " print(\"Yes, 'apple' is in the fruits list\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "e3xQsCS7O45o", "colab_type": "text" }, "source": [ "Exx 11.3 Is" ] }, { "cell_type": "code", "metadata": { "id": "J7e3sguKO_ts", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "d1e84536-2041-4112-b919-8624b7bacb40" }, "source": [ "x1 = 5\n", "y1 = 5\n", "x2 = 'Hello'\n", "y2 = 'Hello'\n", "x3 = [1,2,3]\n", "y3 = [1,2,3]\n", "\n", "\n", "# Output: True\n", "print(x2 is y2)\n", "\n", "# Output: False\n", "print(x3 is y3)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "True\n", "False\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "6Lmg0NJXPNGu", "colab_type": "text" }, "source": [ "Ex 11.4 Is Not" ] }, { "cell_type": "code", "metadata": { "id": "y2TldNZiPHcv", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "92b1908a-c828-40d6-a571-797996eefa42" }, "source": [ "x1 = 5\n", "y1 = 5\n", "x2 = 'Hello'\n", "y2 = 'Hello'\n", "x3 = [1,2,3]\n", "y3 = [1,2,3]\n", "\n", "# Output: False\n", "print(x1 is not y1)\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "False\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "6h2IxCClPbe3", "colab_type": "text" }, "source": [ "**Ex 12 Tuples**" ] }, { "cell_type": "markdown", "metadata": { "id": "F3krnOJTPrTF", "colab_type": "text" }, "source": [ "A tuple is a collection which is ordered and unchangeable. In Python tuples are written with round brackets." ] }, { "cell_type": "markdown", "metadata": { "id": "B2ebMxf5PvKp", "colab_type": "text" }, "source": [ "Ex 12.1 Create a Tuple" ] }, { "cell_type": "code", "metadata": { "id": "XBTZej4aP41F", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "0e338ff0-4997-42dc-8d63-815c047eaf97" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "print(thistuple)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "('apple', 'banana', 'cherry')\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "PaYPkAQAP9hY", "colab_type": "text" }, "source": [ "Ex 12.2 Access Tuple Items" ] }, { "cell_type": "markdown", "metadata": { "id": "o8N1bYAQQGFv", "colab_type": "text" }, "source": [ "You can access tuple items by referring to the index number, inside square brackets:" ] }, { "cell_type": "code", "metadata": { "id": "Jy1ln04vQIrJ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "4985fb24-1519-43f2-ea93-03db6b8cc0b8" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "print(thistuple[1])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "banana\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "EaSvKRJ5QOlZ", "colab_type": "text" }, "source": [ "Ex 12.3 Negative Indexing" ] }, { "cell_type": "markdown", "metadata": { "id": "L-3G_CbaQTuA", "colab_type": "text" }, "source": [ "Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the second last item etc." ] }, { "cell_type": "code", "metadata": { "id": "rVNLq62uQRbK", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "d3c1d569-c3b6-4c57-abc3-9179864a8292" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "print(thistuple[-1])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "cherry\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "L_l8ejf6QZUD", "colab_type": "text" }, "source": [ "Ex 12.4 Slicing tuples" ] }, { "cell_type": "code", "metadata": { "id": "TJEOCbg_Qlgi", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "6e9b3463-ed03-4f09-9576-2d7391294221" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\")\n", "print(thistuple[2:5])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "('cherry', 'orange', 'kiwi')\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "YfbrPDdMiKxQ", "colab_type": "text" }, "source": [ "Ex 12.5 Range of Negative Indexes" ] }, { "cell_type": "markdown", "metadata": { "id": "VIU8PFHViP1a", "colab_type": "text" }, "source": [ "This example returns the items from index -4 (included) to index -1 (excluded)" ] }, { "cell_type": "code", "metadata": { "id": "nZu8pZuViUq4", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "96952984-9010-4255-d670-01b30ed4346b" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\", \"orange\", \"kiwi\", \"melon\", \"mango\")\n", "print(thistuple[-4:-1])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "('orange', 'kiwi', 'melon')\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "vuWODLrEicha", "colab_type": "text" }, "source": [ "Ex 12.6 Change Tuple Values" ] }, { "cell_type": "markdown", "metadata": { "id": "jaxFwsKYiotD", "colab_type": "text" }, "source": [ "Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.\n", "\n", "But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple." ] }, { "cell_type": "code", "metadata": { "id": "68nyZJp2inRG", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "d74f5622-117e-4945-af52-45801937775c" }, "source": [ "x = (\"apple\", \"banana\", \"cherry\")\n", "y = list(x)\n", "y[1] = \"kiwi\"\n", "x = tuple(y)\n", "\n", "print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "('apple', 'kiwi', 'cherry')\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "c8aw6tIsivdx", "colab_type": "text" }, "source": [ "Ex 12.7 Check if Item Exists" ] }, { "cell_type": "markdown", "metadata": { "id": "rE-L_Iadi1Ev", "colab_type": "text" }, "source": [ "To determine if a specified item is present in a tuple use the in keyword:" ] }, { "cell_type": "code", "metadata": { "id": "Vl2DoA-1jHXe", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "537cf437-26b7-4729-a698-3b6ef15c6a97" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "if \"apple\" in thistuple:\n", " print(\"Yes, 'apple' is in the fruits tuple\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Yes, 'apple' is in the fruits tuple\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "Ti8YTOicjJur", "colab_type": "text" }, "source": [ "Ex 12.8 Tuple Length" ] }, { "cell_type": "markdown", "metadata": { "id": "DmCgn4IDjQv9", "colab_type": "text" }, "source": [ "To determine how many items a tuple has, use the len() method" ] }, { "cell_type": "code", "metadata": { "id": "iuBns__EjSLU", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "77697707-68a5-4d06-fd64-d84df75487a5" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "print(len(thistuple))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "3\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "1p-DS6k_jXVM", "colab_type": "text" }, "source": [ "Ex 12.9 Add Items" ] }, { "cell_type": "markdown", "metadata": { "id": "P2seDOmxjcx4", "colab_type": "text" }, "source": [ "Once a tuple is created, you cannot add items to it. Tuples are unchangeable." ] }, { "cell_type": "code", "metadata": { "id": "qIJmt7giVbXC", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "2aad1c60-ecea-4f26-b112-284d6317ddc0" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "thistuple[1] = \"orange\" \n", "print(thistuple)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "['apple', 'orange', 'cherry']\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "JYfwHml4VdDD", "colab_type": "text" }, "source": [ "Ex 12.10 Create Tuple With One Item" ] }, { "cell_type": "markdown", "metadata": { "id": "Wl03Yy73Vyq9", "colab_type": "text" }, "source": [ "To create a tuple with only one item, you have to add a comma after the item, otherwise Python will not recognize it as a tuple." ] }, { "cell_type": "code", "metadata": { "id": "qHnkaKipV1HR", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "9c20a833-2019-4896-bb4f-d7e8cc743168" }, "source": [ "thistuple = (\"apple\",)\n", "print(type(thistuple))\n", "\n", "#NOT a tuple\n", "thistuple = (\"apple\")\n", "print(type(thistuple))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "\n", "\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "P5--n2d0V4_3", "colab_type": "text" }, "source": [ "Ex 12.11 Remove Items" ] }, { "cell_type": "code", "metadata": { "id": "Z25YqEiuV9Ft", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 201 }, "outputId": "da3580cc-99ba-4eb1-a2ed-0f959c9ac4be" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "del thistuple\n", "print(thistuple)" ], "execution_count": null, "outputs": [ { "output_type": "error", "ename": "NameError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\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[0mthistuple\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\"apple\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"banana\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"cherry\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdel\u001b[0m \u001b[0mthistuple\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mthistuple\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'thistuple' is not defined" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "yAgJQ2HTWUIn", "colab_type": "text" }, "source": [ "Tuples are unchangeable, so you cannot remove items from it, but you can delete the tuple completely:" ] }, { "cell_type": "markdown", "metadata": { "id": "5ojgdAjyWesE", "colab_type": "text" }, "source": [ "The del keyword can delete the tuple completely:" ] }, { "cell_type": "code", "metadata": { "id": "HU92CeN-WeLD", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 201 }, "outputId": "3b84a206-dd5b-4d9a-9db8-0be8f086be6d" }, "source": [ "thistuple = (\"apple\", \"banana\", \"cherry\")\n", "del thistuple\n", "print(thistuple)" ], "execution_count": null, "outputs": [ { "output_type": "error", "ename": "NameError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\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[0mthistuple\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m\"apple\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"banana\"\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m\"cherry\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mdel\u001b[0m \u001b[0mthistuple\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mthistuple\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'thistuple' is not defined" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "eHgl4uK1Wqdq", "colab_type": "text" }, "source": [ "Ex 12.12 Join Two Tuples" ] }, { "cell_type": "markdown", "metadata": { "id": "RHs8V2WxWwKm", "colab_type": "text" }, "source": [ "To join two or more tuples you can use the + operator:" ] }, { "cell_type": "code", "metadata": { "id": "xGraAbGKWZ0v", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "68696e99-a5c4-4bda-bc48-c735ad4abb47" }, "source": [ "tuple1 = (\"a\", \"b\" , \"c\")\n", "tuple2 = (1, 2, 3)\n", "\n", "tuple3 = tuple2 + tuple1\n", "print(tuple3)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "(1, 2, 3, 'a', 'b', 'c')\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "YK4cZk7rW2Lx", "colab_type": "text" }, "source": [ "Ex 12.13 The tuple() Constructor" ] }, { "cell_type": "markdown", "metadata": { "id": "k1ifqioMW9QO", "colab_type": "text" }, "source": [ "It is also possible to use the tuple() constructor to make a tuple." ] }, { "cell_type": "code", "metadata": { "id": "PsIpl4DWW-dc", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "401d26a7-5757-4693-8947-8dc8196cbbc7" }, "source": [ "thistuple = tuple((\"apple\", \"banana\", \"cherry\")) # note the double round-brackets\n", "print(thistuple)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "('apple', 'banana', 'cherry')\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "t8-pcf9lhfk_", "colab_type": "text" }, "source": [ "**Ex 13 While Loops**" ] }, { "cell_type": "markdown", "metadata": { "id": "UPbo2vFEhjaj", "colab_type": "text" }, "source": [ "Python has two primitive loop commands:\n", "* while loops\n", "* for loops" ] }, { "cell_type": "markdown", "metadata": { "id": "SQjAuI5GiowN", "colab_type": "text" }, "source": [ "Ex 13.1 While Loops" ] }, { "cell_type": "markdown", "metadata": { "id": "9uhpxYLQiDbP", "colab_type": "text" }, "source": [ "Print i as long as i is less than 6:" ] }, { "cell_type": "code", "metadata": { "id": "GYuNBWVyiGGB", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 104 }, "outputId": "efbd0394-b1a5-4202-9206-9f7d06298341" }, "source": [ "i = 1\n", "while i < 6:\n", " print(i)\n", " i += 1" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "XGSeiz-ciKMy", "colab_type": "text" }, "source": [ "Note: remember to increment i, or else the loop will continue forever." ] }, { "cell_type": "markdown", "metadata": { "id": "8JxNCOatiPAE", "colab_type": "text" }, "source": [ "The while loop requires relevant variables to be ready, in this example we need to define an indexing variable, i, which we set to 1." ] }, { "cell_type": "markdown", "metadata": { "id": "AIP3tUSiikf1", "colab_type": "text" }, "source": [ "Ex 13.2 The break Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "Y8wJ8nPri2e1", "colab_type": "text" }, "source": [ "With the break statement we can stop the loop even if the while condition is true:" ] }, { "cell_type": "markdown", "metadata": { "id": "3wbaaOhEjAWU", "colab_type": "text" }, "source": [ "Exit the loop when i is 3:" ] }, { "cell_type": "code", "metadata": { "id": "dpi-kVhmjG5d", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "72ed854d-f813-48ad-bfc1-95ee26af389b" }, "source": [ "i = 1\n", "while i < 6:\n", " print(i)\n", " if i == 3:\n", " break\n", " i += 1" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "1\n", "2\n", "3\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "taehBHojjN76", "colab_type": "text" }, "source": [ "Ex 13.3 The continue Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "jilL5_31jWAX", "colab_type": "text" }, "source": [ "With the continue statement we can stop the current iteration, and continue with the next:" ] }, { "cell_type": "markdown", "metadata": { "id": "91beXzw6jY3m", "colab_type": "text" }, "source": [ "Continue to the next iteration if i is 3:" ] }, { "cell_type": "code", "metadata": { "id": "eZlx2j2bjaVq", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 104 }, "outputId": "af516936-2d63-4876-8c17-f03b6f793b31" }, "source": [ "i = 0\n", "while i < 6:\n", " i += 1\n", " if i == 3:\n", " continue\n", " print(i)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "1\n", "2\n", "4\n", "5\n", "6\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "G6xW5SXEjk2U", "colab_type": "text" }, "source": [ "Ex 13.4 The else Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "L439IlYejnSR", "colab_type": "text" }, "source": [ "With the else statement we can run a block of code once when the condition no longer is true:" ] }, { "cell_type": "code", "metadata": { "id": "mluA40HqjqcQ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 121 }, "outputId": "30bb61e1-df79-4b56-a8a7-fd728970ce11" }, "source": [ "i = 1\n", "while i < 6:\n", " print(i)\n", " i += 1\n", "else:\n", " print(\"i is no longer less than 6\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "i is no longer less than 6\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "DtkVOCfsDAe_", "colab_type": "text" }, "source": [ "**Ex 14 For Loops**" ] }, { "cell_type": "markdown", "metadata": { "id": "oz_l0AXODK3_", "colab_type": "text" }, "source": [ "Ex 14.1 Python For Loops" ] }, { "cell_type": "markdown", "metadata": { "id": "AQEHnXwiDFG_", "colab_type": "text" }, "source": [ "A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).\n", "\n", "This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.\n", "\n", "With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc." ] }, { "cell_type": "markdown", "metadata": { "id": "ZmgDVXGlDIkN", "colab_type": "text" }, "source": [ "Print each fruit in a fruit list:" ] }, { "cell_type": "code", "metadata": { "id": "NtmqmE3zDPEk", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "cc57fa95-c363-405f-d91e-a992f3ed2216" }, "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for x in fruits:\n", " print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "apple\n", "banana\n", "cherry\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "20fP5jVZD0Kr", "colab_type": "text" }, "source": [ "The for loop does not require an indexing variable to set beforehand." ] }, { "cell_type": "markdown", "metadata": { "id": "38U3758lD1x9", "colab_type": "text" }, "source": [ "Ex 14.2 Looping Through a String" ] }, { "cell_type": "markdown", "metadata": { "id": "7DMuxoFID6mU", "colab_type": "text" }, "source": [ "Even strings are iterable objects, they contain a sequence of characters:" ] }, { "cell_type": "markdown", "metadata": { "id": "zcKd3S8kD9WJ", "colab_type": "text" }, "source": [ "Loop through the letters in the word \"banana\":" ] }, { "cell_type": "code", "metadata": { "id": "INcl-XecD46g", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 121 }, "outputId": "5a903080-c535-4b6b-c604-e1c92aa1160d" }, "source": [ "ba = \"banana\"\n", "for x in ba:\n", " print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "b\n", "a\n", "n\n", "a\n", "n\n", "a\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "OyRAzDStO2cj", "colab_type": "text" }, "source": [ "Ex 14.3 The break Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "9hHPQc2eO5j0", "colab_type": "text" }, "source": [ "With the break statement we can stop the loop before it has looped through all the items:" ] }, { "cell_type": "markdown", "metadata": { "id": "y8LWbyzMO7m6", "colab_type": "text" }, "source": [ "Exit the loop when x is \"banana\":" ] }, { "cell_type": "code", "metadata": { "id": "2N2VJHu7O93x", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "2a11d829-ef45-4518-a1f3-7d0d9490cf49" }, "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for x in fruits:\n", " print(x)\n", " if x == \"banana\":\n", " break\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "apple\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "-aIzULcsPGHA", "colab_type": "text" }, "source": [ "Exit the loop when x is \"banana\", but this time the break comes before the print:" ] }, { "cell_type": "code", "metadata": { "id": "VqVSwmBkPJpg", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "8c33e81e-c12e-41f7-ff04-d1a58d0f6ad7" }, "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for x in fruits:\n", " if x == \"banana\":\n", " break\n", " print(x)\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "apple\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "q5YeOys9PMab", "colab_type": "text" }, "source": [ "Ex 14.4 The continue Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "n6DgEvzgPSXc", "colab_type": "text" }, "source": [ "With the continue statement we can stop the current iteration of the loop, and continue with the next:" ] }, { "cell_type": "markdown", "metadata": { "id": "OLDKjOnZPXbD", "colab_type": "text" }, "source": [ "Do not print banana:\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "VtbRuBOKPbl_", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "5715acb3-7d7f-46a8-8179-22611c66dc60" }, "source": [ "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for x in fruits:\n", " if x == \"banana\":\n", " continue\n", " print(x)\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "apple\n", "cherry\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "4mZ9FEChPec-", "colab_type": "text" }, "source": [ "Ex 14.5 The range() Function" ] }, { "cell_type": "markdown", "metadata": { "id": "qXex6Sn7Pojd", "colab_type": "text" }, "source": [ "To loop through a set of code a specified number of times, we can use the range() function,\n", "\n", "The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number." ] }, { "cell_type": "code", "metadata": { "id": "zSCjZX-iPslk", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 208 }, "outputId": "6a22276b-cd3a-4e4b-e3ab-3adc12da2f49" }, "source": [ "for x in range(11):\n", " print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "XmEYu6-HPvYD", "colab_type": "text" }, "source": [ "Note that range(6) is not the values of 0 to 6, but the values 0 to 5." ] }, { "cell_type": "markdown", "metadata": { "id": "NHcl7yixPzRf", "colab_type": "text" }, "source": [ "The range() function defaults to 0 as a starting value, however it is possible to specify the starting value by adding a parameter: range(2, 6), which means values from 2 to 6 (but not including 6):\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "_fM3CW2kQAAT", "colab_type": "text" }, "source": [ "Using the start parameter:" ] }, { "cell_type": "code", "metadata": { "id": "cY7WlDZwP-Se", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "d5bf0c9a-d975-4cba-d79c-272fef52c105" }, "source": [ "for x in range(2, 6):\n", " print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "2\n", "4\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "JivYJIoFQJ7W", "colab_type": "text" }, "source": [ "The range() function defaults to increment the sequence by 1, however it is possible to specify the increment value by adding a third parameter: range(2, 30, 3):" ] }, { "cell_type": "markdown", "metadata": { "id": "aHWIuLHQQM_X", "colab_type": "text" }, "source": [ "Increment the sequence with 3 (default is 1):" ] }, { "cell_type": "code", "metadata": { "id": "810xjnkjQ8zB", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 191 }, "outputId": "14d54547-5771-4da5-911a-80a6d01385ec" }, "source": [ "for x in range(2, 30, 3):\n", " print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "2\n", "5\n", "8\n", "11\n", "14\n", "17\n", "20\n", "23\n", "26\n", "29\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "aDpYaPPsRAtE", "colab_type": "text" }, "source": [ "Ex 14.6 Else in For Loop" ] }, { "cell_type": "markdown", "metadata": { "id": "M2Cb1DIzRGdN", "colab_type": "text" }, "source": [ "The else keyword in a for loop specifies a block of code to be executed when the loop is finished:" ] }, { "cell_type": "markdown", "metadata": { "id": "AN1HtIy_RHpF", "colab_type": "text" }, "source": [ "Print all numbers from 0 to 5, and print a message when the loop has ended:\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "zTQ-2Ei8RL-P", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 139 }, "outputId": "d6e42b7c-c1f2-45c7-bed6-8d14d810b126" }, "source": [ "for x in range(6):\n", " print(x)\n", "else:\n", " print(\"Finally finished!\")\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n", "5\n", "Finally finished!\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "Lie7G4IaRg_N", "colab_type": "text" }, "source": [ "Ex 14.7 Nested Loops" ] }, { "cell_type": "markdown", "metadata": { "id": "MoUdOfafRlSU", "colab_type": "text" }, "source": [ "A nested loop is a loop inside a loop.\n", "\n", "The \"inner loop\" will be executed one time for each iteration of the \"outer loop\":" ] }, { "cell_type": "code", "metadata": { "id": "SUlHKqFzRo05", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 173 }, "outputId": "30f8e204-f005-415f-d63b-e697aee39700" }, "source": [ "adj = [\"red\", \"big\", \"tasty\"]\n", "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "\n", "for x in adj:\n", " for y in fruits:\n", " print(x, y)\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "red apple\n", "red banana\n", "red cherry\n", "big apple\n", "big banana\n", "big cherry\n", "tasty apple\n", "tasty banana\n", "tasty cherry\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "AqWR8Gf_TbDG", "colab_type": "text" }, "source": [ "Ex 14.8 The pass Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "9IV-lSVETfME", "colab_type": "text" }, "source": [ "for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error." ] }, { "cell_type": "code", "metadata": { "id": "zpiA7mFnTiUr", "colab_type": "code", "colab": {} }, "source": [ "for x in [0, 1, 2]:\n", " pass" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "y3I_6Ri1EFRp", "colab_type": "text" }, "source": [ "**Ex 15 Dictionary**" ] }, { "cell_type": "markdown", "metadata": { "id": "DQTG6NDeEkXO", "colab_type": "text" }, "source": [ "Ex 15.1 Dictionary" ] }, { "cell_type": "markdown", "metadata": { "id": "LmyzDAkfEymp", "colab_type": "text" }, "source": [ "A dictionary is a collection which is unordered, changeable and indexed. In Python dictionaries are written with curly brackets, and they have keys and values." ] }, { "cell_type": "code", "metadata": { "id": "CHfPEQzYExet", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "f6e43dd2-0a0c-4a70-a3af-6ac871cf915e" }, "source": [ "thisdict = {\n", " \"Pranay\": 254367,\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'Pranay': 254367, 'model': 'Mustang', 'year': 1964}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "TDzQNmlLFRBZ", "colab_type": "text" }, "source": [ "Ex 15.2 Accessing Items" ] }, { "cell_type": "markdown", "metadata": { "id": "5dD1Y6lGFt8J", "colab_type": "text" }, "source": [ "You can access the items of a dictionary by referring to its key name, inside square brackets:" ] }, { "cell_type": "markdown", "metadata": { "id": "Wh_t8dDHFxhb", "colab_type": "text" }, "source": [ "Get the value of the \"model\" key:" ] }, { "cell_type": "code", "metadata": { "id": "JjgevG7lF9-4", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "fa910294-202d-4d62-fe07-dc1d92b878e1" }, "source": [ "x = thisdict[\"Pranay\"]\n", "print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "254367\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "Itxdr7gbGBAF", "colab_type": "text" }, "source": [ "There is also a method called get() that will give you the same result:" ] }, { "cell_type": "code", "metadata": { "id": "_Y2sBzxlGEJv", "colab_type": "code", "colab": {} }, "source": [ "x = thisdict.get(\"model\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "a0-J89RKGRIC", "colab_type": "text" }, "source": [ "Ex 15.3 Change Values" ] }, { "cell_type": "markdown", "metadata": { "id": "79MUWe0EGcMG", "colab_type": "text" }, "source": [ "You can change the value of a specific item by referring to its key name:" ] }, { "cell_type": "markdown", "metadata": { "id": "QkL0iMVzGfaK", "colab_type": "text" }, "source": [ "Change the \"year\" to 2018:" ] }, { "cell_type": "code", "metadata": { "id": "-xX71M9bGbas", "colab_type": "code", "colab": {} }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict[\"year\"] = 2020" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "__0EbC9cGrNH", "colab_type": "text" }, "source": [ "Ex 15.4 Loop Through a Dictionary" ] }, { "cell_type": "markdown", "metadata": { "id": "4X3D-kJMHE8f", "colab_type": "text" }, "source": [ "You can loop through a dictionary by using a for loop.\n", "\n", "When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well." ] }, { "cell_type": "code", "metadata": { "id": "HRLcCTaBHGCa", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/" }, "outputId": "71fdb315-5af3-47a8-8740-ff178527cf7d" }, "source": [ "for x in thisdict:\n", " print(x)\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "brand\n", "model\n", "year\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "QjvUwft2YYcm", "colab_type": "text" }, "source": [ "Print all values in the dictionary, one by one:" ] }, { "cell_type": "code", "metadata": { "id": "yUPzL42OYaVv", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "46af3f50-66e3-4afc-97fb-ae3fa8e52cb0" }, "source": [ "for x in thisdict:\n", " print(thisdict[x])" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Ford\n", "Mustang\n", "2018\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "QfOzdHeNYfXn", "colab_type": "text" }, "source": [ "You can also use the values() method to return values of a dictionary:" ] }, { "cell_type": "code", "metadata": { "id": "fynrV0boYhBR", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "3858b7f0-6a4a-453d-f670-96ff3f95a741" }, "source": [ "for x in thisdict.values():\n", " print(x)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Ford\n", "Mustang\n", "2018\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "jA33lkNjYmOG", "colab_type": "text" }, "source": [ "Loop through both keys and values, by using the items() method:" ] }, { "cell_type": "code", "metadata": { "id": "1xmSzcHtYo3L", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 68 }, "outputId": "30e909f8-7319-46b7-8646-2fa023719c3c" }, "source": [ "for x, y in thisdict.items():\n", " print(x, y)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "brand Ford\n", "model Mustang\n", "year 2018\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "3HOETc4UYse4", "colab_type": "text" }, "source": [ "Ex 15.6 Check if Key Exists" ] }, { "cell_type": "markdown", "metadata": { "id": "5pFYRp3YYwlf", "colab_type": "text" }, "source": [ "To determine if a specified key is present in a dictionary use the in keyword:" ] }, { "cell_type": "markdown", "metadata": { "id": "mjcWHTUzYzPB", "colab_type": "text" }, "source": [ "Check if \"model\" is present in the dictionary:" ] }, { "cell_type": "code", "metadata": { "id": "geRQIllkY2KO", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "d2027796-905b-4387-8880-ea1e91a0f2f3" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "if \"model\" in thisdict:\n", " print(\"Yes, 'model' is one of the keys in the thisdict dictionary\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Yes, 'model' is one of the keys in the thisdict dictionary\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "wXIEKqrxY5Aw", "colab_type": "text" }, "source": [ "Ex 15.7 Dictionary Length" ] }, { "cell_type": "markdown", "metadata": { "id": "zhyb2TW-Y8qF", "colab_type": "text" }, "source": [ "To determine how many items (key-value pairs) a dictionary has, use the len() function." ] }, { "cell_type": "code", "metadata": { "id": "R7FOndJlY_TN", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "02138a5b-192a-4bc1-ef7d-7d27e9eed197" }, "source": [ "print(len(thisdict))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "3\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "WGLe2az4ZDAP", "colab_type": "text" }, "source": [ "Ex 15.8 Adding Items" ] }, { "cell_type": "markdown", "metadata": { "id": "E5fWsF9cZG9b", "colab_type": "text" }, "source": [ "Adding an item to the dictionary is done by using a new index key and assigning a value to it:" ] }, { "cell_type": "code", "metadata": { "id": "pVhOe5GiZJ45", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "67579e6e-dab2-40ff-d4cf-4a38673f2a8c" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict[\"color\"] = \"red\"\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "wa6tKpEpZM1e", "colab_type": "text" }, "source": [ "Ex 15.9 Removing Items" ] }, { "cell_type": "markdown", "metadata": { "id": "k0poXfXiZQaC", "colab_type": "text" }, "source": [ "There are several methods to remove items from a dictionary:" ] }, { "cell_type": "markdown", "metadata": { "id": "Yo89YCxAZSvE", "colab_type": "text" }, "source": [ "The pop() method removes the item with the specified key name:\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "rzFqGdMGZVVo", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "9076bd06-8b1f-41d0-b3d3-57581ffdccdc" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict.pop(\"model\")\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'year': 1964}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "AR9n57eKZZx-", "colab_type": "text" }, "source": [ "The popitem() method removes the last inserted item (in versions before 3.7, a random item is removed instead):\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "KMH9Ar3JZYqq", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "193cb7ed-fbe7-4675-a614-a2765faf4d66" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict.popitem()\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'model': 'Mustang'}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "KGyXsaYSZgKd", "colab_type": "text" }, "source": [ "The del keyword removes the item with the specified key name:" ] }, { "cell_type": "code", "metadata": { "id": "u7x5FR5BZi3Q", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "bfad569c-3de5-450a-f3e8-e3b8f056a3e7" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "del thisdict[\"model\"]\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'year': 1964}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "MP2E6fKxZ-93", "colab_type": "text" }, "source": [ "Ex 15.10 Deleting Elements" ] }, { "cell_type": "markdown", "metadata": { "id": "69N7frWqaCrw", "colab_type": "text" }, "source": [ "The del keyword can also delete the dictionary completely:" ] }, { "cell_type": "code", "metadata": { "id": "oc9ZVAEnaCHU", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 199 }, "outputId": "72474421-98b3-4116-9fcc-4c2d2c061fdc" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "del thisdict\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "error", "ename": "NameError", "evalue": "ignored", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\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 5\u001b[0m }\n\u001b[1;32m 6\u001b[0m \u001b[0;32mdel\u001b[0m \u001b[0mthisdict\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 7\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mthisdict\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'thisdict' is not defined" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "OjV7NPj1aLEC", "colab_type": "text" }, "source": [ "The clear() method empties the dictionary:" ] }, { "cell_type": "code", "metadata": { "id": "f6BgbZkoaKU5", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "d0e79e09-a468-493c-d4cf-b70bc6af5789" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "thisdict.clear()\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "VTqnGMWpaR6V", "colab_type": "text" }, "source": [ "Ex 15.11 Copy a Dictionary" ] }, { "cell_type": "code", "metadata": { "id": "VU7IKE4nc8Vp", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 52 }, "outputId": "5ab5cd2e-4eec-422c-e6d0-adf21ff5eca4" }, "source": [ "dict1 = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "dict2 = dict1\n", "print(dict2)\n", "dict1[\"brand\"] = \"farari\"\n", "print(dict2)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n", "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "_yKcq8eAapAY", "colab_type": "text" }, "source": [ "You cannot copy a dictionary simply by typing dict2 = dict1, because: dict2 will only be a reference to dict1, and changes made in dict1 will automatically also be made in dict2.\n", "\n", "There are ways to make a copy, one way is to use the built-in Dictionary method copy()." ] }, { "cell_type": "markdown", "metadata": { "id": "ijlhD98_arpQ", "colab_type": "text" }, "source": [ "Make a copy of a dictionary with the copy() method:" ] }, { "cell_type": "markdown", "metadata": { "id": "_KikmmGyauPg", "colab_type": "text" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "mydict = thisdict.copy()\n", "print(mydict)" ] }, { "cell_type": "markdown", "metadata": { "id": "y-zSjGxMaxI5", "colab_type": "text" }, "source": [ "Another way to make a copy is to use the built-in function dict().\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "iWE4GQ-6a4Pj", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "06aaffcf-0bf7-48d2-f007-3cffe65278bb" }, "source": [ "thisdict = {\n", " \"brand\": \"Ford\",\n", " \"model\": \"Mustang\",\n", " \"year\": 1964\n", "}\n", "mydict = dict(thisdict)\n", "print(mydict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "BJNeoOOaez6g", "colab_type": "text" }, "source": [ "Ex 15.12 Nested Dictionaries" ] }, { "cell_type": "markdown", "metadata": { "id": "04m0i9ooe5Pw", "colab_type": "text" }, "source": [ "A dictionary can also contain many dictionaries, this is called nested dictionaries." ] }, { "cell_type": "markdown", "metadata": { "id": "rAc1IdLufFAk", "colab_type": "text" }, "source": [ "Create a dictionary that contain three dictionaries:\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "v9nkrhjPe4u-", "colab_type": "code", "colab": {} }, "source": [ "myfamily = {\n", " \"child1\" : {\n", " \"name\" : \"Emil\",\n", " \"year\" : 2004\n", " },\n", " \"child2\" : {\n", " \"name\" : \"Tobias\",\n", " \"year\" : 2007\n", " },\n", " \"child3\" : {\n", " \"name\" : \"Linus\",\n", " \"year\" : 2011\n", " }\n", "}" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "qptWxQFdfR6X", "colab_type": "text" }, "source": [ "Or, if you want to nest three dictionaries that already exists as dictionaries:" ] }, { "cell_type": "markdown", "metadata": { "id": "tNmbykDufVSf", "colab_type": "text" }, "source": [ "Create three dictionaries, then create one dictionary that will contain the other three dictionaries:" ] }, { "cell_type": "code", "metadata": { "id": "3vkqst64fX0G", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 55 }, "outputId": "9ae9bb3a-7f55-432b-8d62-6ee95c4c77f1" }, "source": [ "child1 = {\n", " \"name\" : \"Emil\",\n", " \"year\" : 2004\n", "}\n", "child2 = {\n", " \"name\" : \"Tobias\",\n", " \"year\" : 2007\n", "}\n", "child3 = {\n", " \"name\" : \"Linus\",\n", " \"year\" : 2011\n", "}\n", "myfamily = {\n", " \"child1\" : child1,\n", " \"child2\" : child2,\n", " \"child3\" : child3\n", "}\n", "print(myfamily)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'child1': {'name': 'Emil', 'year': 2004}, 'child2': {'name': 'Tobias', 'year': 2007}, 'child3': {'name': 'Linus', 'year': 2011}}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "Rn3vZbxAfakK", "colab_type": "text" }, "source": [ "Ex 15.13 The dict() Constructor" ] }, { "cell_type": "markdown", "metadata": { "id": "rdlaOAkJfeTI", "colab_type": "text" }, "source": [ "It is also possible to use the dict() constructor to make a new dictionary:\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "oOPG4UuwffYa", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 34 }, "outputId": "bdcd30f1-797e-4775-c489-4a7f0a644eb0" }, "source": [ "thisdict = dict(brand=\"Ford\", model=\"Mustang\", year=1964)\n", "# note that keywords are not string literals\n", "# note the use of equals rather than colon for the assignment\n", "print(thisdict)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "{'brand': 'Ford', 'model': 'Mustang', 'year': 1964}\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "qw2OJQgFmkRM", "colab_type": "text" }, "source": [ "**Ex 16 Functions**" ] }, { "cell_type": "markdown", "metadata": { "id": "G9Jle1FsU4vr", "colab_type": "text" }, "source": [ "A function is a block of code which only runs when it is called.\n", "\n", "You can pass data, known as parameters, into a function.\n", "\n", "A function can return data as a result." ] }, { "cell_type": "markdown", "metadata": { "id": "CCcLQNxXU7jO", "colab_type": "text" }, "source": [ "Ex 16.1 Creating a Function" ] }, { "cell_type": "markdown", "metadata": { "id": "vnA9ZS9AVbUg", "colab_type": "text" }, "source": [ "In Python a function is defined using the def keyword:" ] }, { "cell_type": "code", "metadata": { "id": "9B2IKF8kVdff", "colab_type": "code", "colab": {} }, "source": [ "def my_function():\n", " print(\"Hello from a function\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "uK0a2496VZi_", "colab_type": "text" }, "source": [ "Ex 16.2 Calling a Function" ] }, { "cell_type": "markdown", "metadata": { "id": "cKRf-IZqV1zc", "colab_type": "text" }, "source": [ "To call a function, use the function name followed by parenthesis:" ] }, { "cell_type": "code", "metadata": { "id": "PWTlqnd7V4ZZ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "21096f4e-95fb-498e-bcff-b83ada836473" }, "source": [ "def my_function():\n", " print(\"Hello from a function\")\n", "\n", "my_function()" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Hello from a function\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "DLeEjaYkV-wq", "colab_type": "text" }, "source": [ "Ex 16.3 Arguments" ] }, { "cell_type": "markdown", "metadata": { "id": "EjW0XRvWWDPf", "colab_type": "text" }, "source": [ "Information can be passed into functions as arguments.\n", "\n", "Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.\n", "\n", "The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name:" ] }, { "cell_type": "code", "metadata": { "id": "VmsjNu59WHI4", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "22ae007f-0675-4300-db4a-f7db34592285" }, "source": [ "def my_function(fname):\n", " print(fname + \" Refsnes\")\n", " \n", "my_function(\"Emil\")\n", "my_function(\"Tobias\")\n", "my_function(\"Linus\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Emil Refsnes\n", "Tobias Refsnes\n", "Linus Refsnes\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "1olXK0SRYHxG", "colab_type": "text" }, "source": [ "Ex 16.4 Parameters or Arguments?" ] }, { "cell_type": "markdown", "metadata": { "id": "HVUhVT0kYMUb", "colab_type": "text" }, "source": [ "The terms parameter and argument can be used for the same thing: information that are passed into a function." ] }, { "cell_type": "markdown", "metadata": { "id": "UnLKYg4iYOKS", "colab_type": "text" }, "source": [ "From a function's perspective:\n", "\n", "A parameter is the variable listed inside the parentheses in the function definition.\n", "\n", "An argument is the value that is sent to the function when it is called." ] }, { "cell_type": "markdown", "metadata": { "id": "ZHpQ_CaXYUzU", "colab_type": "text" }, "source": [ "Ex 16.5 Number of Arguments" ] }, { "cell_type": "markdown", "metadata": { "id": "_fdAbvwnYbRe", "colab_type": "text" }, "source": [ "By default, a function must be called with the correct number of arguments. Meaning that if your function expects 2 arguments, you have to call the function with 2 arguments, not more, and not less." ] }, { "cell_type": "markdown", "metadata": { "id": "GrE8ZGG5Yevg", "colab_type": "text" }, "source": [ "This function expects 2 arguments, and gets 2 arguments:" ] }, { "cell_type": "code", "metadata": { "id": "fWZ3lH7OYKf6", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "db6b08a0-05ea-40ce-c73c-15d06532a60b" }, "source": [ "def my_function(fname, lname):\n", " print(fname + \" \" + lname)\n", "\n", "my_function(\"Emil\", \"Refsnes\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Emil Refsnes\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "-0zBY-ohYw-r", "colab_type": "text" }, "source": [ "Errors" ] }, { "cell_type": "code", "metadata": { "id": "8DOVzagqYpMd", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 201 }, "outputId": "c252a106-7221-453c-c365-7046c229c564" }, "source": [ "def my_function(fname, lname):\n", " print(fname + \" \" + lname)\n", "\n", "my_function(\"Emile\")" ], "execution_count": null, "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 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mfname\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m\" \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mlname\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mmy_function\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Emile\"\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: my_function() missing 1 required positional argument: 'lname'" ] } ] }, { "cell_type": "markdown", "metadata": { "id": "ljGXaFX4Yt1z", "colab_type": "text" }, "source": [ "If you try to call the function with 1 or 3 arguments, you will get an error:" ] }, { "cell_type": "markdown", "metadata": { "id": "wj4QTs4mY-ey", "colab_type": "text" }, "source": [ "Ex 16.6 Arbitrary Arguments, *args" ] }, { "cell_type": "markdown", "metadata": { "id": "M0CJfbl_ZdE3", "colab_type": "text" }, "source": [ "If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.\n", "\n", "This way the function will receive a tuple of arguments, and can access the items accordingly:" ] }, { "cell_type": "markdown", "metadata": { "id": "2RGkiH-0Zj6I", "colab_type": "text" }, "source": [ "If the number of arguments is unknown, add a * before the parameter name:" ] }, { "cell_type": "code", "metadata": { "id": "rt3Ziw1YH1hf", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "7e0cef3d-6207-47c2-f229-310f62613cd2" }, "source": [ "def my_function(*kids):\n", " print(\"The youngest child is \" + kids[1:-1])\n", "\n", "my_function(\"Emil\", \"Tobias\", \"Linus\", \"rishi\", \"pranay\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "The youngest child is Tobias\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "L12UrjEsH5Vy", "colab_type": "text" }, "source": [ "Arbitrary Arguments are often shortened to *args in Python documentations." ] }, { "cell_type": "markdown", "metadata": { "id": "rwOheAw2JCms", "colab_type": "text" }, "source": [ "\n", "Ex 16.7 Keyword Arguments" ] }, { "cell_type": "markdown", "metadata": { "id": "z0sjNaV2ITWd", "colab_type": "text" }, "source": [ "You can also send arguments with the key = value syntax.\n", "\n", "This way the order of the arguments does not matter." ] }, { "cell_type": "code", "metadata": { "id": "yRAuh54NIgrw", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "cc20bc1b-07a4-4b1f-ad7d-f897a4591f1c" }, "source": [ "def my_function(child3, child2, child1):\n", " print(\"The youngest child is \" + child3)\n", "\n", "my_function(child1 = \"Emil\", child2 = \"Tobias\", child3 = \"Linus\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "The youngest child is Linus\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "eIFEaBE4I8uM", "colab_type": "text" }, "source": [ "The phrase Keyword Arguments are often shortened to kwargs in Python documentations." ] }, { "cell_type": "markdown", "metadata": { "id": "H4U0eRhEK4kX", "colab_type": "text" }, "source": [ "\n", "Ex 16.8 Arbitrary Keyword Arguments, **kwargs" ] }, { "cell_type": "markdown", "metadata": { "id": "RovuuqvyLXmd", "colab_type": "text" }, "source": [ "If you do not know how many keyword arguments that will be passed into your function, add two asterisk: ** before the parameter name in the function definition.\n", "\n", "This way the function will receive a dictionary of arguments, and can access the items accordingly:" ] }, { "cell_type": "markdown", "metadata": { "id": "iJPYf4SVLbcU", "colab_type": "text" }, "source": [ "If the number of keyword arguments is unknown, add a double ** before the parameter name:" ] }, { "cell_type": "code", "metadata": { "id": "nKtadjpzLeZN", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "d73859b6-c57e-4d11-9613-a7b30c49aa86" }, "source": [ "def my_function(**kid):\n", " print(\"His last name is \" + kid[\"lname\"])\n", "\n", "my_function(fname = \"Tobias\", lname = \"Refsnes\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "His last name is Refsnes\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "sdC0OgLxLs8D", "colab_type": "text" }, "source": [ "Arbitrary Kword Arguments are often shortened to **kwargs in Python documentations." ] }, { "cell_type": "markdown", "metadata": { "id": "qHS0q7CCMjDL", "colab_type": "text" }, "source": [ "Ex 16.9 Default Parameter Value" ] }, { "cell_type": "markdown", "metadata": { "id": "5JvbNupCNulV", "colab_type": "text" }, "source": [ "The following example shows how to use a default parameter value.\n", "\n", "If we call the function without argument, it uses the default value:" ] }, { "cell_type": "code", "metadata": { "id": "dl7vivfmNv1t", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 87 }, "outputId": "6cfacdc0-b7a7-443b-f460-1199ac318dfe" }, "source": [ "def my_function(country = \"Norway\"):\n", " print(\"I am from \" + country)\n", "\n", "my_function(\"Sweden\")\n", "my_function(\"India\")\n", "my_function()\n", "my_function(\"Brazil\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "I am from Sweden\n", "I am from India\n", "I am from Norway\n", "I am from Brazil\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "CtuC7X9XN06E", "colab_type": "text" }, "source": [ "Ex 16.10 Passing a List as an Argument" ] }, { "cell_type": "markdown", "metadata": { "id": "a8TmZH7GOJlq", "colab_type": "text" }, "source": [ "You can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function.\n", "\n", "E.g. if you send a List as an argument, it will still be a List when it reaches the function:\n" ] }, { "cell_type": "code", "metadata": { "id": "Ol_W81BlOLaJ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "78fceb03-b829-48ac-e813-bf1cec6a69fd" }, "source": [ "def my_function(food):\n", " for x in food:\n", " print(x)\n", "\n", "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "\n", "my_function(fruits)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "apple\n", "banana\n", "cherry\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "HJ0wzHEuO2yo", "colab_type": "text" }, "source": [ "Ex 16.11 Return Values" ] }, { "cell_type": "markdown", "metadata": { "id": "-NhgGUZhPFda", "colab_type": "text" }, "source": [ "To let a function return a value, use the return statement:" ] }, { "cell_type": "code", "metadata": { "id": "3cuRr6qKPHgh", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "861c57b0-7367-451e-ae2d-d2e5fca9d6a3" }, "source": [ "def my_function(x):\n", " return 5 * x\n", "\n", "print(my_function(3))\n", "print(my_function(5))\n", "print(my_function(9))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "15\n", "25\n", "45\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "3slAo68IPLv3", "colab_type": "text" }, "source": [ "Ex 16.12 The pass Statement" ] }, { "cell_type": "markdown", "metadata": { "id": "ZI5XpZQKPriA", "colab_type": "text" }, "source": [ "function definitions cannot be empty, but if you for some reason have a function definition with no content, put in the pass statement to avoid getting an error." ] }, { "cell_type": "code", "metadata": { "id": "rTAPUq1OPuvk", "colab_type": "code", "colab": {} }, "source": [ "def myfunction():\n", " pass" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "GUJseepCVqwR", "colab_type": "text" }, "source": [ "Ex 16.13 Recursion" ] }, { "cell_type": "markdown", "metadata": { "id": "S-s0U02RVvq6", "colab_type": "text" }, "source": [ "Python also accepts function recursion, which means a defined function can call itself.\n", "\n", "Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.\n", "\n", "The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.\n", "\n", "In this example, tri_recursion() is a function that we have defined to call itself (\"recurse\"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).\n", "\n", "To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it." ] }, { "cell_type": "code", "metadata": { "id": "7XWspbIIVufU", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 191 }, "outputId": "0dc47c42-9e50-4086-a798-ee8ac60c5015" }, "source": [ "def tri_recursion(k):\n", " if(k > 0):\n", " result = k + tri_recursion(k - 1)\n", " print(result)\n", " else:\n", " result = 0\n", " return result\n", "\n", "print(\"\\n\\nRecursion Example Results\")\n", "tri_recursion(6)" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "\n", "\n", "Recursion Example Results\n", "1\n", "3\n", "6\n", "10\n", "15\n", "21\n" ], "name": "stdout" }, { "output_type": "execute_result", "data": { "text/plain": [ "21" ] }, "metadata": { "tags": [] }, "execution_count": 8 } ] }, { "cell_type": "markdown", "metadata": { "id": "Z0jHyAIsZ_w7", "colab_type": "text" }, "source": [ "Ex 17 Python User-defined Functions" ] }, { "cell_type": "markdown", "metadata": { "id": "JMZg-ocKaZGQ", "colab_type": "text" }, "source": [ "**What are user-defined functions in Python?**" ] }, { "cell_type": "markdown", "metadata": { "id": "nY_EnbZ0ah3b", "colab_type": "text" }, "source": [ "Functions that we define ourselves to do certain specific task are referred as user-defined functions. The way in which we define and call functions in Python are already discussed.\n", "\n", "Functions that readily come with Python are called built-in functions. If we use functions written by others in the form of library, it can be termed as library functions.\n", "\n", "All the other functions that we write on our own fall under user-defined functions. So, our user-defined function could be a library function to someone else." ] }, { "cell_type": "markdown", "metadata": { "id": "RQtstxPUayW3", "colab_type": "text" }, "source": [ "**Advantages of user-defined functions**" ] }, { "cell_type": "markdown", "metadata": { "id": "j5V4W-K9a9uq", "colab_type": "text" }, "source": [ "1. User-defined functions help to decompose a large program into small segments which makes program easy to understand, maintain and debug.\n", "2. If repeated code occurs in a program. Function can be used to include those codes and execute when needed by calling that function.\n", "3. Programmars working on large project can divide the workload by making different functions." ] }, { "cell_type": "code", "metadata": { "id": "kFUEarT3bR8H", "colab_type": "code", "colab": {} }, "source": [ "" ], "execution_count": null, "outputs": [] }, { "cell_type": "code", "metadata": { "id": "SV4OaD_baj67", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 35 }, "outputId": "975a4691-cf31-434e-ad8f-a6cad9e665f9" }, "source": [ "# Program to illustrate\n", "# the use of user-defined functions\n", "\n", "def add_numbers(x,y):\n", " sum = x + y\n", " return sum\n", "\n", "num1 = 5\n", "num2 = 6\n", "\n", "print(\"The sum is\", add_numbers(num1, num2))" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "The sum is 11\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "ikTf5-IgW1jL", "colab_type": "text" }, "source": [ "**Ex Programs**" ] }, { "cell_type": "markdown", "metadata": { "id": "KwHIm2WDW7et", "colab_type": "text" }, "source": [ "Ex 1 Calculator" ] }, { "cell_type": "code", "metadata": { "id": "saH6nA2Bgxhn", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 87 }, "outputId": "00c2eace-e2f0-4433-83be-a97415383034" }, "source": [ "first_no = int(input(\"Enter the first no.: \"))\n", "second_no = int(input(\"Enter the second no.: \"))\n", "symbol = input(\"Enter a symbol of the computations you want to perform. (i.e +, -, *, /) \")\n", "if symbol == \"+\":\n", " print(first_no + second_no)\n", "elif symbol == \"-\":\n", " print(first_no - second_no)\n", "elif symbol == \"*\":\n", " print(first_no * second_no)\n", "elif symbol == \"/\":\n", " if second_no != 0:\n", " print(first_no / second_no)\n", " else:\n", " print(\"You can not divide a number with 0\")\n", "else:\n", " print(\"invalid symbol\")\n", "\n" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Enter the first no.: 0\n", "Enter the second no.: 10\n", "Enter a symbol of the computations you want to perform. (i.e +, -, *, /) /\n", "0.0\n" ], "name": "stdout" } ] }, { "cell_type": "markdown", "metadata": { "id": "1Vm_-5VnO6BJ", "colab_type": "text" }, "source": [ "Ex 2 Palindrome." ] }, { "cell_type": "code", "metadata": { "id": "BLIr3iUOZ4jZ", "colab_type": "code", "colab": { "base_uri": "https://localhost:8080/", "height": 69 }, "outputId": "f95c6184-a0aa-4e0e-eceb-61d1a101e66d" }, "source": [ "name = input(\"Enter the string: \")\n", "name = name.lower()\n", "print(name)\n", "palindrome = name[::-1]\n", "if palindrome == name:\n", " print(\"yes, the number is palindrome.\")\n", "else:\n", " print(\"no, its not a palindrome.\")" ], "execution_count": null, "outputs": [ { "output_type": "stream", "text": [ "Enter the string: naman\n", "naman\n", "yes, the number is palindrome.\n" ], "name": "stdout" } ] }, { "cell_type": "code", "metadata": { "id": "8dfzgAZHRAET", "colab_type": "code", "colab": {} }, "source": [ "" ], "execution_count": null, "outputs": [] } ] }