{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Introduction to Python Programming - Part - II\n", "Instructor: Dr. Sanasam Ranbir Singh
\n", "This tutorial is prepared by Mr. Vijay Purohit, Dept. of CSE, IIT Guwahati" ] }, { "cell_type": "markdown", "metadata": { "id": "B2EpV4Z9WYxF" }, "source": [ "### **1. FUNCTIONS**\n", "---\n", "* *It is a named unit of a group of program statment. It can be invoked from other parts of the program as and when require.*\n", "* *It is basically a subprogram that acts on a data and can returns data.*\n", "\n", "> **Relatable f:X→Y y=f(x)?**\n", "![data_types.jpg](https://upload.wikimedia.org/wikipedia/commons/3/3b/Function_machine2.svg)\n", "\n", "* **User Defined Functions**: These are defined by the user at the time of writing a program as per requirements of the program.\n", "* **Built-in (or Library) funtions**: There are the part of library, as we have seen in last class print(), int(), float(), input()\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "P5Ruy11PaAN3" }, "outputs": [], "source": [ "#Some Built-In Funtions: input(), float(), type(), print() \n", "price = float(input('Enter the price: ')) \n", "print(type(price)) \n", "print(\"Current Price mentioned is {}\".format(price)) \n", "print(f\"The cost is {price} Rupees.\")" ] }, { "cell_type": "markdown", "metadata": { "id": "gi9tWn8EdCy5" }, "source": [ "### **2. Function Definition and Call**\n", "```\n", "def function_name(parameter: data_type) -> return_type: \n", " \"\"\" docstring \"\"\"\n", " # body of the function\n", " return expression\n", "``` \n", "\n", "* Take Care of Indentation\n", "* To execute a funtion, you must *call it*\n", "* When a function is called, the interpreter jumps to that function and executed the statments in its block. Then, when the end of the block is reached, the interpreter jumps back to the part of the prgram that called the function, and the program resmes execution at that point.\n", "\n", "![funtion_def.jpg](https://media.geeksforgeeks.org/wp-content/uploads/20220721172423/51.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "15jSMrCdfdwh", "outputId": "5c2c671e-e2bf-4e98-febe-ecf4517f2369" }, "outputs": [], "source": [ "#We defined a function named message. (notice the colon)\n", "def message(): \n", " print(\"Welcome to LAB-02.\")\n", "\n", "#call the message function\n", "message()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "nEFMpe4Xitri" }, "outputs": [], "source": [ "#FLOW OF PROGRAM\n", "print(\"1. statment BEFORE the function definiton with parameters\")\n", "#Function Definition with PARAMETERS \n", "def message(name): \n", " print(\"Welcome to LAB-02 of \"+name)\n", "\n", "print(\"2. statment AFTER the function definiton\")\n", "\n", "#call the message function with ARGUMENTS\n", "message(\"Python class\")\n", "\n", "print(\"3. statment AFTER the function CALL with Arguments\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "GN2ed70ChwqK" }, "outputs": [], "source": [ "#for people with prior experience in langugages like c/c++ or java \n", "# def add2nums(num1, num2) -> int: #with syntax 1\n", "def add2nums(num1: int, num2: int) -> int: #with syntax 2 data type -> return type\n", " \"\"\" This functions add two numbers\"\"\" #doc string \n", " num3 = num1+num2\n", " return num3 # return statment\n", "\n", "num1, num2 = 5, 10\n", "ans = add2nums(num1, num2) #function call\n", "print(f\"The addition of {num1} and {num2} is: {ans}.\") \n", "\n", "# about docstring\\\n", "#Syntax: print(function_name.__doc__)\n", "#print(add2nums.__doc__)" ] }, { "cell_type": "markdown", "metadata": { "id": "cAv5e8m1LaAj" }, "source": [ "### **3. Types of Arguments**\n", "\n", "* **Default Arguments**: \n", "Once we have a default argument, all the arguments to its right must also have default values." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "F8CswblsO50E" }, "outputs": [], "source": [ "#def fun_arg(x=1, y, z=3):\n", "def fun_arg(x, y, z=3):\n", " print(\"x: \", x)\n", " print(\"y: \", y)\n", " print(\"z: \", z) \n", "\n", "#fun_arg(1, 2)\n", "fun_arg(1, 2, 4)" ] }, { "cell_type": "markdown", "metadata": { "id": "Ae4BJ7YvQC3t" }, "source": [ "* **Keyword Arguments**: \n", "Using this way, the order(position) of the arguments can be changed.\n", "Keyword arguments must follow positional arguments." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "rlbenkA9RaJf", "outputId": "e1a18bb2-5832-44ce-de72-4d4279770ca1" }, "outputs": [], "source": [ "def courseName(firstName, lastName):\n", " print(firstName, lastName)\n", "\n", "courseName(firstName=\"Python-\", lastName=\"Programming\") #keywords arguments\n", "courseName(lastName=\"Programming \", firstName=\"Python-\") #out of order\n", "courseName(\"Python-\", lastName=\"Programming 2\") #1 positional, 1 keyword" ] }, { "cell_type": "markdown", "metadata": { "id": "2aSXQ9A2SySm" }, "source": [ "* **Variable Length Arguments:**\n", "variable number of arguments to a function\n", "1. `*args` (non-keyword arguments)\n", "2. `**kwargs` (keyword arguments)\n", "\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "o3-InmBnTTCV", "outputId": "55773499-6cf9-47eb-cc86-0527022fac12" }, "outputs": [], "source": [ "def varArgs(*argv):\n", " for item in argv:\n", " print(item, end=\"-\")\n", "\n", "varArgs('1', '2', '3', '4', '5', '6', '7', '8', '9')\n", "print()\n", "def varArgs(**keyArgv):\n", " for key,value in keyArgv.items():\n", " print(key,\"-\", value, end=\"|\")\n", "\n", "varArgs(one='1', two='2', three='3', four='4', five='5', six='6', seven='7', eight='8', nine='9')" ] }, { "cell_type": "markdown", "metadata": { "id": "KNGV_wgdWgQH" }, "source": [ "### **4. Return Statement**\n", "```\n", "syntax: return [expression_list]\n", "```\n", "It can consist of a variable, an expression, or a constant which is returned to the end of the function execution\n" ] }, { "cell_type": "markdown", "metadata": { "id": "RsjjuobcXmBQ" }, "source": [ "### **5. Recursive Function**\n", "A function calling itself.\n", "![recursive approach](https://cdn.programiz.com/cdn/farfuture/6i17bRQT6hWIqw9JE5rMMyW527g7It_68T7kSzpIplo/mtime:1591262415/sites/tutorial2program/files/python-recursion-function.png)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "TtXh6AoWX5PP" }, "outputs": [], "source": [ "def factorial(x):\n", " \"\"\"This is a recursive function to find the factorial of an integer\"\"\" \n", " print(x, end='*')\n", " if x == 1:\n", " return 1\n", " else:\n", " return (x * factorial(x-1))\n", "num = 6\n", "print(\"\\nThe factorial of\", num, \"is\", factorial(num))\n" ] }, { "cell_type": "markdown", "metadata": { "id": "wMncp2xzY7sI" }, "source": [ "More about it [here](https://cdn.programiz.com/sites/tutorial2program/files/python-factorial-function.png)" ] }, { "cell_type": "markdown", "metadata": { "id": "HOFRcYqLZfJH" }, "source": [ "### **6.Variables Type**\n", "* **Global Variables**\n", "A variable declared outside of the function or in global scope." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "2__Z_t0IaocB" }, "outputs": [], "source": [ "x = \"global\" \n", "def foo():\n", " print(\"inside foo func:\", x) \n", "foo()\n", "print(\"main:\", x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Wz4TDTOraoM_", "outputId": "a6dc864d-9846-426e-f098-715d00519c05" }, "outputs": [], "source": [ "x = \"global\" \n", "def foo():\n", " #global x\n", " x = x*2\n", " print(\"inside foo func:\", x) \n", "foo()\n", "print(\"main:\", x)" ] }, { "cell_type": "markdown", "metadata": { "id": "eZfGhgEQbwZA" }, "source": [ "* **Local Variables**\n", "A variable declared inside the function's body or in the local scope.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "HbgCzQBQcYru" }, "outputs": [], "source": [ "\n", "def foo():\n", " y = \"local\" \n", " print(\"inside foo func:\", y) \n", "foo()\n", "print(\"main:\", y) #error" ] }, { "cell_type": "markdown", "metadata": { "id": "m0eZ9H90gtCk" }, "source": [ "### **7. Modules**\n", "A file that contains Python code.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Lo2n5YVGg25r", "outputId": "c59a3c8a-a4ba-4f3c-a39b-5ba1b87ec3f9" }, "outputs": [], "source": [ "import math\n", "#import math as m\n", "def area(radius):\n", " #return m.pi * radius**2\n", " return math.pi * radius**2\n", "area(3.4)" ] }, { "cell_type": "markdown", "metadata": { "id": "ZbSNGAKNhedb" }, "source": [ "### **LISTS AND TUPLES**\n", "\n", "A **sequence** is an object that contains multiple items of data.\n", "**Two** of the Fundamental Sequence Types: **lists and tuples**. \n", "* Both can hold various types of data.\n", "* **Difference**: a list is mutable, which means that a program can change its contents.\n", "Surrounded by square brackets `[ ]`\n", "* But a tuple is immutable, which means that once it is created, its contents cannot be changed.\n", "Surrounded by parenthesis `( )`" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "n4nTgZj4ndQX", "outputId": "d4a103df-3cd9-444a-b418-139c28948e9e" }, "outputs": [], "source": [ "# List of even integers\n", "even = [2, 4, 6, 8, 10]\n", "print(\"even: \",even)\n", "print(\"even size: \",len(even)) #length of list\n", "\n", "# List of names\n", "names = [\"python\", \"c++\", \"rust\"]\n", "print(\"names: \",names)\n", "\n", "# List with mixed data types\n", "mixture = [1, \"Hi\", 3.4]\n", "print(\"mixture: \",mixture)\n", "print(\"mixture size: \",len(mixture)) #size of list\n", "\n", "# Nested List\n", "nested = [\"top\", [8, 4, 6], ['a']]\n", "print(\"nested: \",nested)\n", "print(\"nested size: \",len(nested)) #size of list\n", "\n", "# list() function to convert type of objects to list\n", "numbers = list(range(1, 10, 2))\n", "print(\"numbers: \",numbers)" ] }, { "cell_type": "markdown", "metadata": { "id": "5ie-IbQfw9mq" }, "source": [ "### **1. Accessing Elements**\n", "* Refer to the index number. Use the index operator [ ] to access an item in a list. \n", "* The index must be an integer. \n", "* Nested lists are accessed using nested indexing. " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "D1LdplfcxEIR" }, "outputs": [], "source": [ "# Nested List\n", "nested = [\"top\", [8, 4, 6], ['a']]\n", "print(\"nested[0]: \",nested[0]) # 1st element\n", "print(\"nested[1]: \",nested[1])\n", "print(\"nested[1][0]: \",nested[1][0]) # multi-dimension\n", "print(\"nested[2]: \",nested[2])" ] }, { "cell_type": "markdown", "metadata": { "id": "kyLqtYzYxqgK" }, "source": [ "* **Negative Indexing**\n", " * represent positions from the end of the array. (means beginning from the end).\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "1DGVZXZWx3Nb" }, "outputs": [], "source": [ "# Nested List\n", "nested = [\"top\", [8, 4, 6], ['a']]\n", "print(\"nested[-1]: \",nested[-1]) # last element\n", "print(\"nested[-3]: \",nested[1]) #last third item\n", "print(\"nested[1][-1]: \",nested[1][-1]) # multi-dimension" ] }, { "cell_type": "markdown", "metadata": { "id": "VHOHBGw0zAIy" }, "source": [ "### **2. List Functions**\n", "**2a. Append Method:**\n", "one element/tuple/existinglist at a time can be added to the list by using append() function" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "D8EIOTUizWX0", "outputId": "e0679f40-c3b6-4ecd-836c-8dfe7501f9d5" }, "outputs": [], "source": [ "even = [2]\n", "even.append(8) #append elements\n", "even.append(12)\n", "print(\"even: \",even) \n", " \n", "names = [\"python\", ]\n", "names.append((\"c++\", \"java\")) #append tuples\n", "print(\"names: \",names)\n", "\n", "nested = [\"top\", 'a']\n", "nested.append(even)\n", "print(\"nested: \",nested)" ] }, { "cell_type": "markdown", "metadata": { "id": "htPqLv4bz9rz" }, "source": [ "**2b. Insert Method:**\n", "To insert elements at the desired position\n", "```\n", "list.insert(position, value)\n", "``` " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "9IGuGu1v0VUz", "outputId": "d246be29-5161-4ca1-dbe0-b6286518c30d" }, "outputs": [], "source": [ "even = [2, 8, 12]\n", "even.insert(1, 4) \n", "print(\"even: \",even) \n", "even.insert(3, 10) \n", "print(\"even: \",even) " ] }, { "cell_type": "markdown", "metadata": { "id": "r7DiQaQa02Bc" }, "source": [ "**2c. Remove Method**\n", "remove the first occurrence of the specified item" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "zgivmpfF07j7", "outputId": "4af728b0-4de9-44c2-c1d3-dc1bdba49a91" }, "outputs": [], "source": [ "even = [2, 4, 8, 12, 4]\n", "even.remove(4) \n", "print(\"even: \",even) \n", "even.remove(4) \n", "print(\"even: \",even) " ] }, { "cell_type": "markdown", "metadata": { "id": "7KkL1cKM1VTa" }, "source": [ "**2d. Pop Method**\n", "by default remove only the last element of the list. To remove an element from specific position of the list, the index of the element is passed as an argument.\n", "\n", "* **Del Statment**" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "itOpWKxa1sfq", "outputId": "c5166083-bb1f-4854-f433-8afe4d02ac5c" }, "outputs": [], "source": [ "even = [2, 4, 8, 12, 4]\n", "item = even.pop() \n", "print(\"item: \",item) \n", "print(\"pop even: \",even) \n", "even.pop(1) \n", "print(\"pop even: \",even) \n", "\n", "even = [2, 4, 8, 12, 4]\n", "del even[2] \n", "print(\"del even: \",even) " ] }, { "cell_type": "markdown", "metadata": { "id": "1qNblmz318qJ" }, "source": [ "**2e. Sort Method**\n", "sort elements in ascending order\n", "\n", "**2f. Reverse Method**\n", "reverse the list" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "UBvOePCx18qJ", "outputId": "c3f1a8f4-fda0-4fc0-d1b0-4d2be9f1512a" }, "outputs": [], "source": [ "even = [2, 4, 8, 12]\n", "even.reverse() \n", "print(\"even: \",even) \n", "\n", "even = [14, 12, 8, 4, 2] \n", "even.sort()\n", "print(\"even: \",even) " ] }, { "cell_type": "markdown", "metadata": { "id": "4Br5bQes2K3p" }, "source": [ "**2g. min and max function**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "BLxh8QpP3r9t", "outputId": "5e386a53-fb9f-4fd9-a12c-e8fede113e3d" }, "outputs": [], "source": [ "even = [12, 4, 16, 8, 10, 2, 22]\n", "print(\"min in even: \",min(even))\n", "print(\"max in even: \",max(even))" ] }, { "cell_type": "markdown", "metadata": { "id": "i0zbx5-N4NlH" }, "source": [ "### **3. Some Operations on Lists**\n", "\n", "**3a. Contcatenating Lists**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PRCxzjzv4a9F", "outputId": "815d9d29-3d5b-4b50-f6fd-e21ed8b8e019" }, "outputs": [], "source": [ "list1 = [1, 2, 3, 4]\n", "list2 = [8, 7, 6, 5]\n", "list3 = list1 + list2 \n", "print(list3)" ] }, { "cell_type": "markdown", "metadata": { "id": "H-yTli8K43NW" }, "source": [ "**3b. Copying Lists**\n", "both lists will reference the same list in the memory" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "_NHx_qzm5CUk" }, "outputs": [], "source": [ "list1 = [1, 2, 3, 4]\n", "list2 = [8, 7, 6, 5]\n", "list2 = list1 #both lists will reference the same list in the memory\n", "list1[0] = 0\n", "print(list1)\n", "print(list2)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "sF_CVnX35ik2" }, "outputs": [], "source": [ "list1 = [1, 2, 3, 4]\n", "list2 = []+list1 #different copy\n", "list1[0] = 0\n", "print(list1)\n", "print(list2)" ] }, { "cell_type": "markdown", "metadata": { "id": "t1D_KFZZ6CKd" }, "source": [ "**3c. Finding items in Lists Using in Operator** \n", "```\n", "syntax: item in list\n", "```\n", "returns true if item is found in the list, or false otherwise\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "MZfhPQTQ6Ysf", "outputId": "a4fedd59-e55d-46d5-89c3-30fca8467824" }, "outputs": [], "source": [ "list1 = [1, 2, 8, 7, 6, 5, 3, 4] \n", "if 3 in list1:\n", " print(\"found\")\n", "else:\n", " print(\"not found\")" ] }, { "cell_type": "markdown", "metadata": { "id": "HkBUCaMd_3IJ" }, "source": [ "**3d. * operator (repetition operator)**\n", "```\n", "syntax: list * n\n", "left side: list\n", "right side: integer\n", "```\n", "It makes multiple copies of a list and joins them all together\n", "\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "6U-xC3qRAaep", "outputId": "1a574e98-05f7-4420-faea-73de56bf8903" }, "outputs": [], "source": [ "numbers = [1,2,3]*3\n", "print(numbers)" ] }, { "cell_type": "markdown", "metadata": { "id": "qs0i6ylt6zeH" }, "source": [ "### **4. List Slicing**\n", "**slices:** subsections of a sequence\n", "```\n", "list_name[start: end]\n", "```\n", "* start is the index of the first element.\n", "* end is the index marking the end of the slice\n", "* elements include from start up (but not including) end\n", "\n", "![](https://media.geeksforgeeks.org/wp-content/uploads/List-Slicing.jpg)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "AHvC6Jqo7bUN", "outputId": "aa6513db-13f9-491f-8b03-4df102b9d2e1" }, "outputs": [], "source": [ "days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']\n", "mid_days = days[2:5]\n", "print(\"days: \",days) \n", "print(\"mid_days: \",mid_days) \n", "\n", "first2_days = days[:2] # elements from begining till given index\n", "print(\"first2_days: \",first2_days) \n", "\n", "last_days = days[5:] # elements from specific index till the end\n", "print(\"last_days: \",last_days) \n", "\n", "all_days = days[:] # \n", "print(\"all_days: \",all_days) \n", "\n", "numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] \n", "even = numbers[1:8:2] # step value of 2 \n", "print(\"even: \",even) \n", "\n", "n = numbers[-5:] #negative indexing\n", "print(\"n: \",n)\n", "\n", "all = numbers[::-1] #in reverse order\n", "print(\"all: \",all) \n" ] }, { "cell_type": "markdown", "metadata": { "id": "siNkHFEH-Ayw" }, "source": [ "### **5. Two Dimensional Lists**\n", "nested list or two-dimensional lists\n", " \n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "8jifwpCD-Moe", "outputId": "309e044f-4e3e-4440-cf50-41d95bbd2b33" }, "outputs": [], "source": [ "matrix = [[4, 17, 34, 24], [46, 21, 54, 10], [54, 92, 20, 100]]\n", "for r in range(3):\n", " for c in range(4):\n", " print(matrix[r][c], end=\" \")\n", " print()" ] }, { "cell_type": "markdown", "metadata": { "id": "5FQA9BbQ_VF5" }, "source": [ "### **6. TUPLES**\n", "* A tuple is a sequence, like a list.\n", "* immutable, once created cannot be changed.\n", "* enclosed in parentheses `( )`\n", "* support all the same operations as lists, except those that change the contents.\n", "\n", "* **supports**\n", " * len, min, max, in, +, * \n", " * slicing expressions, index, subscript indexing\n", "* **does not supports**\n", " * append, remove, insert, reverse, and sort\n", "\n", "* adv:\n", " * faster performance\n", " * safe\n", "\n", "\n", "\n", "```\n", "tuple_name = tuple(str_list)\n", "```\n", "\n" ] }, { "cell_type": "markdown", "metadata": { "id": "Y4QAMOlB_GMh" }, "source": [ "### **STRINGS**\n", "* strings are immuatable\n", "\n", "### **1. Accessing Individual Characters in a String**\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "jsuMANDqBbTK", "outputId": "b7217671-f89b-4a97-f74f-32a583dfce73" }, "outputs": [], "source": [ "name =\"Python Programming\"\n", "for ch in name:\n", " print(ch, end=\"-\")\n", "print()\n", "ch = name[5]\n", "print(\"ch: \", ch)\n", "\n", "\n", "print(\"len of name: \", len(name)) #length function" ] }, { "cell_type": "markdown", "metadata": { "id": "q3JHWO9HCcDa" }, "source": [ "### **2. String Concatenation** " ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "FFSOZBr4CrwC", "outputId": "84a706d2-414f-4808-ac95-fcd09ff94d37" }, "outputs": [], "source": [ "message = \"Hello\" + ' ' + \"world\"\n", "print(message)" ] }, { "cell_type": "markdown", "metadata": { "id": "wREQo3l5DJHK" }, "source": [ "### **3. String Slicing**\n", "**slices:** substrings of a string\n", "```\n", "string[start: end]\n", "```\n", "* start is the index of the first character.\n", "* end is the index marking the end of the slice\n", "* return a string containing a copy of the characters from start up to (but not including) end." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "F8lF33mjDqcr", "outputId": "c7f05d0c-f6a0-46de-f78b-0c0971b8383e" }, "outputs": [], "source": [ "full_name = \"Amar Akbar Anthony\"\n", "middle_name = full_name[5:10]\n", "print(\"middle_name[5:10]: \",middle_name)\n", "\n", "first_name = full_name[:4]\n", "print(\"first_name[5:10]: \",first_name)\n", "\n", "last_name = full_name[11:]\n", "print(\"last_name[11:]: \",last_name)\n", "\n", "last_name_neg = full_name[-6:]\n", "print(\"last_name_neg[-6:]: \",last_name_neg)\n", "\n", "name = full_name[:]\n", "print(\"name[:]: \",name)\n", "\n", "letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n", "print(\"letters \",letters[0:26:2]) #step value of 2" ] }, { "cell_type": "markdown", "metadata": { "id": "3u0HEW8sFIaL" }, "source": [ "### **4. TESTING, SEARCHING AND MANUPULATING STRINGS**\n", "general format for string method call\n", "```\n", "syntax: stringvar.method(arguments)\n", "```\n", "\n", "### **4a. Testing Strings with `in` and `not in`**\n", "```\n", "syntax: string1 in string2\n", "```" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "IdxYKklfFduc", "outputId": "e5658843-80df-4444-df67-0ebb973f0451" }, "outputs": [], "source": [ "text = 'Four and seven years ago'\n", "if 'seven' in text:\n", " print('The string \"seven\" was found.')\n", "else:\n", " print('The string \"seven\" was not found.')\n", "\n", "names = 'Amar akbar anthony ram shyam vijay'\n", "if 'ravan' not in names:\n", " print('ravan was not found.')\n", "else:\n", " print('ravan was found.')" ] }, { "cell_type": "markdown", "metadata": { "id": "72JQVyW4GSk0" }, "source": [ "### **4b. String Testing Methods**\n", " \n", "more ref: [here](https://www.geeksforgeeks.org/python-string-methods/)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "0K8MTbu4Gkpp", "outputId": "e544a4b6-b311-4884-8cc4-02782ad2ec05" }, "outputs": [], "source": [ "string1 = '1200'\n", "#string1 = '1200abc'\n", "if string1.isdigit():\n", " print(string1, 'contains only digits.')\n", "else:\n", " print(string1, 'contains characters other than digits.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "dp0oyzpmGySd" }, "outputs": [], "source": [ "# This program demonstrates several string testing methods.\n", "def main():\n", " user_string = input('Enter a string: ') \n", " # Test the string.\n", " if user_string.isalnum():\n", " print('The string is alphanumeric.')\n", " if user_string.isdigit():\n", " print('The string contains only digits.')\n", " if user_string.isalpha():\n", " print('The string contains only alphabetic characters.')\n", " if user_string.isspace():\n", " print('The string contains only whitespace characters.')\n", " if user_string.islower():\n", " print('The letters in the string are all lowercase.')\n", " if user_string.isupper():\n", " print('The letters in the string are all uppercase.')\n", "\n", "#Call the string.\n", "main()" ] }, { "cell_type": "markdown", "metadata": { "id": "O_dF6KD2HS3w" }, "source": [ "**4c. String Modification Methods**\n", "\n", " returns modified versions of strings\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "PCsRcNiSlVDx", "outputId": "65220da7-525d-4d3c-afad-2d1004f4c795" }, "outputs": [], "source": [ "# This program demonstrates several string testing methods.\n", "user_string = \"Wx Yz Ab cde\"\n", "print(\"lower: \", user_string.lower())\n", "print(\"lower: \", user_string.upper())" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "N2vt1WrTmGbj", "outputId": "f2202586-9f47-402a-f3b8-b13eb483c58f" }, "outputs": [], "source": [ "#endswith(substring): returns true if the string ends with substring\n", "filename = \"data.txt\"\n", "if filename.endswith('.txt'):\n", " print('That is the name of a text file.')\n", "else:\n", " print('Unknown file type.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "zvPdJQ3JmWjs", "outputId": "e7f39ad4-8fc1-46c7-c829-9bbdc2ca0ed7" }, "outputs": [], "source": [ "#find(substring): returns the lowest index in the string where substring is found. else returns −1.\n", "string = 'Four and seven years ago'\n", "position = string.find('seven')\n", "if position != -1:\n", " print('The word \"seven\" was found at index', position)\n", "else:\n", " print('The word \"seven\" was not found.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "Uam34aimm46F", "outputId": "375d0609-edc6-44b9-9e38-6f07bc1c0a8a" }, "outputs": [], "source": [ "#replace(old, new) returns a copy of the string with all instances of old replaced by new.\n", "string = 'Four and seven years ago'\n", "new_string = string.replace('years', 'days')\n", "print(new_string)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "z7DEXiCznJJv", "outputId": "79045a74-ff8b-42d2-94af-5e137888167b" }, "outputs": [], "source": [ "#repetition operator *\n", "print('Hello' * 5)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "colab": { "base_uri": "https://localhost:8080/" }, "id": "DeHkPdWgnTiZ", "outputId": "0da85c7e-2cb4-49f6-8b22-30db46c88bf5" }, "outputs": [], "source": [ "# split() : returns a list containing the words in the string.\n", "my_string = 'One two three four' \n", "# Split the string.\n", "word_list = my_string.split()\n", "print(word_list[1])\n", "print(word_list)\n", "\n", "date_string = '11/26/2018'\n", "date_list = date_string.split('/')\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "colab": { "name": "Lab-02 CS594.ipynb", "provenance": [], "toc_visible": true }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.9.12" } }, "nbformat": 4, "nbformat_minor": 1 }