{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# **Functions and Objects in Python**\n", "\n", "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Table of contents:\n", "\n", "1. [Comments](#Comments)\n", "1. [Functions](#Functions)\n", "1. [Object Oriented Programming](#Object-Oriented-Programming)\n", "1. [Membership Operator](#Membership-Operator)\n", "1. [Identity Operator](#Identity-Operator)\n", "1. [Type Casting](#Type-Casting)\n", "1. [range, zip, enumerate and len](#range,-zip,-enumerate-and-len)\n", "1. [String Functions](#String-Functions)\n", "1. [List Functions](#List-Functions)\n", "1. [Dictionary Functions](#Dictionary-Functions)\n", "1. [A few file-handling functions](#A-few-file-handling-functions)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Comments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When working with any programming language, you include comments in the code to notate your work. This details what certain parts of the code are for, and lets other developers – you included – know what you were up to when you wrote the code. This is a necessary practice, and good developers make heavy use of the comment system. Without it, things can get real confusing, real fast.\n", "\n", "> [Python for Beginners - Comments](https://www.pythonforbeginners.com/comments/comments-in-python)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Comments are used to write things in a program that are not executed. They are used to add readability to the program, and allow the programmer to add \"comments\" to the code for the reader of the code." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "#This is a comment in Python" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'This is not a comment.'" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"\"\"This is not a comment.\"\"\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "[Python does not have multiline comments](https://www.codecademy.com/en/forum_questions/505ba3cfc6addb000200e33c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A function is a block of code that can be called with a single line. We alias the block of code(a set of statements) with a name, and then we can use it when needed by *calling* the function (referencing the name) of that block of code. This allows for **reusability of code**." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "def my_func():\n", " print(\"This is a function.\")\n", " print(\"I do not need to type this code again and again now.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "*def* is a Python keyword that identifies that what follows is a function name and definition." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that no output is generated for the above code. That is becuase the above statements only define that my_func refers to the statements in the following code block.\n", "\n", "Also notice how the indentation is crucial here. The moment the indentation ends, (i.e. the next line does not have the indent), the function definition is said to have been completed." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "This is a function.\n", "I do not need to type this code again and again now.\n" ] } ], "source": [ "my_func()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To execute the statements in my_func, we *call* it.\n", "\n", "The way to differentiate a variable from a function is the round brackets *()* following the name." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's consider that we want to compare 2 numbers, and print the square of the first one if it is bigger, or the cube of the second one if that one is bigger. What do we do?" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000\n" ] } ], "source": [ "a = 5\n", "b = 10\n", "if a>b:\n", " print(a*a)\n", "else:\n", " print(b*b*b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we can convert this into a function, but will we always use the same numbers for our decision? What if we want to compare 2 numbers that we calculated after some processing? How can we make functions dynamic to use values we provide them with?\n", "\n", "- Option A: Take user input every time within the function. (Not the best solution)\n", "- Option B: Arguments to a function" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Arguments are values we can give the function, so that it can operate based on those values. This allows functions to have a wide range of usability.\n", "\n", "The variables that are used as arguments have to be defined during function declaration." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def compare_nums(a,b):\n", " if a>b:\n", " print(a*a)\n", " else:\n", " print(b*b*b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The arguments are mentioned inside the brackets. They become variables that get their value when we call the function. We can use them and base the internal execution of the function on those arguments." ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000\n" ] } ], "source": [ "compare_nums(5,10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As shown above, we can pass the values to the function inside the round brackets.\n", "\n", "The order of the arguments in the function definition is maintained, hence the first value passed to it will be the first argument mentioned in the definition of the function, the second one will be second and so on." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Default Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An added layer of functionality is default arguments. We can set default values to variables which we take as arguments in a function, so that if the user of the function does not intend to provide that value, we can function assuming the default value for that function." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "def default_arguments_compare_nums(a=5,b=10):\n", " if a>b:\n", " print(a*a)\n", " else:\n", " print(b*b*b)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "compare_nums() missing 2 required positional arguments: 'a' and 'b'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mcompare_nums\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: compare_nums() missing 2 required positional arguments: 'a' and 'b'" ] } ], "source": [ "compare_nums()" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000\n" ] } ], "source": [ "default_arguments_compare_nums()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can only provide values for a few of the default arguments as well!" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "225\n" ] } ], "source": [ "default_arguments_compare_nums(15)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can have a combination of normal required arguments and default arguments as well.\n", "One important syntactical note:\n", "- For the above, we will need to mention all the default arguments at the end of the list of arguments mentioned inside the brackets." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "def three_arg(a, b=10, c=15):\n", " print(a,b,c)" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "non-default argument follows default argument (, line 1)", "output_type": "error", "traceback": [ "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m def three_arg(b=10,a,c=15):\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m non-default argument follows default argument\n" ] } ], "source": [ "def three_arg(b=10,a,c=15):\n", " print(a,b,c)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In short, required arguments are compulsory, and need to be given. Default arguments can be ommitted." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Keyword Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python allows functions to be called using keyword arguments. When we call functions in this way, the order (position) of the arguments can be changed. Following calls to the above function are all valid and produce the same result." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [], "source": [ "def keyword_args_compare_nums(a=5,b=10):\n", " if a>b:\n", " print(a*a)\n", " else:\n", " print(b*b*b)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000\n" ] } ], "source": [ "keyword_args_compare_nums(a=5, b=10)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000\n" ] } ], "source": [ "keyword_args_compare_nums(b=10)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1000\n" ] } ], "source": [ "keyword_args_compare_nums(b=10, a=5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You can mix positional arguments and keyword arguments in a function call as well. Just ensure all keyword arguments are after the positional arguments." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Arbitrary Arguments" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When we do not know the number of arguments to expect in a function, we use an asterisk (\\*) before the parameter name to denote an arbitrary number of arguments. " ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "def arbit_args(*args):\n", " print(type(args))\n", " for arg in args:\n", " print(arg)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "A\n", "B\n", "1\n", "2\n", "3\n", "44.5\n", "True\n" ] } ], "source": [ "arbit_args(\"A\",\"B\",1,2,3,44.5, True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As we can see, the arguments are packed into a tuple, and given to the function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Return Values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, you may want to use a function to do some processing for you, and give back to you the result of that. That is made possible using return values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Each function can return values, using the *return* keyword." ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [], "source": [ "def find_units_dig(num):\n", " unit_dig = num % 10\n", " #print(unit_dig)\n", " return unit_dig" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "return_val = find_units_dig(11)" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n" ] } ], "source": [ "print(return_val)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In Python you can return multiple values as well. It will automatically put all the return values in a **tuple**, and return it." ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "def ret_multiple_vals():\n", " return 1,3,5,7,9" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "ret_val = ret_multiple_vals()" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "tuple" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(ret_val)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Tuple Unpacking" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For any tuple, we can *unpack* it, by assigning each of it's elements to individual variables. But, instead of accessing each element individually by indexing, we can do it in one line by using tuple unpacking." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [], "source": [ "a,b,c,d,e = ret_multiple_vals()" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 3 5 7 9\n" ] } ], "source": [ "print(a,b,c,d,e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that if the number of variables we assign values to is not equal to the nummber of values in the tuple, Python will give us an error." ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "too many values to unpack (expected 3)", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mc\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mret_multiple_vals\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mValueError\u001b[0m: too many values to unpack (expected 3)" ] } ], "source": [ "a,b,c = ret_multiple_vals()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "print('*',end = '')\n", "```\n", "\n", "We used this to avoid the defualt new line at the end of every print statement.\n", "\n", "Now, we can clearly understand that *print* is a function, it takes as arguments a combination of an arbitrary number of arguments and keyword arguments.\n", "\n", "The keyword argument *end* allows us to tell the print function what to print after the given text on the screen." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "```python\n", "input(\"Random String\")\n", "```\n", "\n", "This allows us to print something onto the screen while expecting input, and returns as a string whatever the input was." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Time for a few exercises:\n", "- Write a function that returns the tens and hundreds place digit of a number.\n", "- Write a function that finds the average of any number of inputs." ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [], "source": [ "def tens_hundreds(num):\n", " return num%10,num%100" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "def avg_nums(*args):\n", " sum_nums = 0\n", " count = 0\n", " for num in args:\n", " sum_nums+=num\n", " count+=1\n", " return sum_nums/count" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Object Oriented Programming" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Traditional programming languages like C are *Procedural*, in that they focus on modules of computatition, and they contain a **series of steps to be carried out**. It is how we normally think of programming. It relies on procedures." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Object oriented programming** is based on the concepts of objects, which contain data and procedures to act on the data." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider an object as an entity, like yourself. Now, you have certain *attributes* like your name, date of birth, phone number and so on. These are stored as data for an object. You are an *object* here." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, consider a program to deal with students, from a college's standpoint. You are just one of the **many** students. For the college, each student will have certain values for a common set of attributes they are interested in. Now, we model each student using a *class*. An object is an instance of a class. It means that the class serves as a blueprint for object generation.\n", "\n", "In the above example, the college may want to provide some functionality custom defined for the use case. They can define them within the class, " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classes and Objects" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we move on to classes and objects, the things I have been telling you about for so long." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What if we want to define our own datatype?\n", "\n", "For example, if we wanted to support a student record, which included their name, roll number and current grade, we would want to have one variable we could access for one student's record, instead of 3.\n", "\n", "- We could use a list.\n", "\n", "But now, what if you wanted to define some custom functions specific to that task? Like calculating the current grade given the last grade and the grade for this semester?\n", "\n", "Just using a function here could lead to problems. Ideally, you would want to keep all of the code relevant to this student entity together. Here, we use classes and objects.\n", "\n", "This also allows us to use operators on custom defined class objects. (I'll get to that in a bit.)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### A class is a collection of methods relevant to a particular entity, and data." ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "class StudentRecord:\n", " def __init__(self, name, roll_no):\n", " print(\"Initialising\",name)\n", " self.grade = 0\n", " self.name = name\n", " self.roll_no = roll_no\n", " #self.year = #3rd and 4th digits of roll_no\n", " def print_self(self):\n", " print(self)\n", " print(type(self))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note the syntax requirements:\n", "- class is a keyword, followed by the class name\n", "- A colon follows, just like we do whenever we have an indented block following a keyword (for, while, if, etc.)\n", "- \\__init__() is a compulsory method that is executed each time we create an object of that class." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### The concept of self" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, every object can have it's own values of variables. But, the function belongs to a class.\n", "\n", "For each student, they need to have their own copy of each variable, since they will have different values(obviously). Hence, we need to find a way to refer to these values within the class functions.\n", "\n", "Python always adds a default argument to every class method call. If the method is called via an object(*object_name.method_name()*), the object is passed to method as the first argument. In most programs we call this variable **self**. We could call it anything else, it is just a variable, that will have object assigned to it." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, to define variables that every object can have unique values for, we use *self.var_name*. All this is done when an object is vreated, hence these statements are written inside \\__init__(). Other arguments mentioned in \\__init__() are the arguments needed to be passed to the class for object creation." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Initialising an object is done via typing the class name followed by round brackets, containing the arguments to \\__init__.**" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialising Aditya\n" ] } ], "source": [ "student_1 = StudentRecord(\"Aditya\",111603029)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialising Elon\n" ] } ], "source": [ "student_2 = StudentRecord(\"Elon\", 111600000)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Aditya\n" ] } ], "source": [ "print(student_1.name)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "111603029\n" ] } ], "source": [ "print(student_1.roll_no)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Elon\n" ] } ], "source": [ "print(student_2.name)" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "111600000\n" ] } ], "source": [ "print(student_2.roll_no)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Hence, for every method inside a class, we have to consider an additional argument during function definition, which will contain the object that has been referred to." ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'print_self' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint_self\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mNameError\u001b[0m: name 'print_self' is not defined" ] } ], "source": [ "print_self()" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "print_self() missing 1 required positional argument: 'self'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mStudentRecord\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mprint_self\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: print_self() missing 1 required positional argument: 'self'" ] } ], "source": [ "StudentRecord.print_self()" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.StudentRecord object at 0x00000228114C1198>\n", "\n" ] } ], "source": [ "StudentRecord.print_self(student_1)" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialising ABC\n", "<__main__.StudentRecord object at 0x00000228114C1EB8>\n", "\n" ] } ], "source": [ "StudentRecord(\"ABC\", 111111111).print_self()" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.StudentRecord object at 0x00000228114C1198>\n", "\n" ] } ], "source": [ "student_1.print_self()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thus as we can see above, the method inside a class cannot be called without an object calling it, or unless an object is passed to it as self and the classname is referred to." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(student_1))" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [], "source": [ "a = 5" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(a))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, notice one thing. The variable a is of type **class int**, just like student_1 is of type **class StudentRecord**(ignore the \\__main__, that's just to tell us that we have defined it in this program.\n", "\n", "Thus, we can now see how our integer is also a class named int, and it's objects are the values that can be assigned to it.\n", "\n", "The variable a is an object of classs int." ] }, { "cell_type": "code", "execution_count": 46, "metadata": {}, "outputs": [], "source": [ "my_list = [5,6,7,10,'A',55.5]" ] }, { "cell_type": "code", "execution_count": 47, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(my_list))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, try this for each datatype. You will notice that everything is of type *class* followed by a class_name. **Hence, we commonly say that almost everything in Python is an object!!** Because even your basic variables are objects, all datatypes are nothing but classes!!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### A little about the 'Power of Python' : Dunder methods" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [], "source": [ "class Abc:\n", " def __init__(self):\n", " print(\"Initialising.\")\n", " def __add__(self, other):\n", " print(\"I'm adding now.\")\n", " print(self)\n", " print(other)" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialising.\n" ] } ], "source": [ "a1 = Abc()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialising.\n" ] } ], "source": [ "a2 = Abc()" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm adding now.\n", "<__main__.Abc object at 0x00000228114CC198>\n", "<__main__.Abc object at 0x00000228114CC160>\n" ] } ], "source": [ "a1+a2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "What just happened?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We used these things called *dunder* methods to support commonly used operators on custom classes.\n", "\n", "Since even datatypes in Python are nothing but classes, these methods exist, to allow us to implement what is commonly known as 'operator overloading' without too much hassle!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Double Underscore, or dunder for short, also called magic methods, support inbuilt functionality common to all objects. There are a lot of these,, and the ease with which we can use them is what makes Python so good." ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [], "source": [ "class Abc:\n", " def __init__(self):\n", " print(\"Initialising.\")\n", " def __add__(self, other):\n", " print(\"I'm adding now.\")\n", " print(self)\n", " print(other)\n", " def __str__(self):\n", " return \"I'm' Abc\"" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initialising.\n" ] } ], "source": [ "a3 = Abc()" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I'm' Abc\n" ] } ], "source": [ "print(a3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thus, \\__str__ allows us to dictate what gets printed when we call print function with the object of that class as an argument." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Remember lists, sets, dictionaries and tuples? They can store any *Object*. That means, they can also store user defined objects." ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [], "source": [ "l1 = [a1, student_1, 1, 2, 'A']" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(l1))" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.Abc at 0x228114cc198>" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "l1[0]" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "s1 = {a1, student_1, 1, 2}" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{1,\n", " 2,\n", " <__main__.Abc at 0x228114cc198>,\n", " <__main__.StudentRecord at 0x228114c1198>}" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "d1 = {a1:student_1, 2:0}" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.StudentRecord at 0x228114c1198>" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "d1[a1]" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [], "source": [ "t1 = (a1, s1, 1, 2)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.Abc at 0x228114cc198>" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "t1[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Membership Operator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To check whether a value is a member of a list, string, tuple or set, we use the membership operator." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The membership operator is the keyword **in**. We can also use **not in**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It evaluates to a boolean value, hence it can be used in conditions. We do not need to write a for loop to check if an element is a member of a collectible datatype. We simply use the keyword in." ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [], "source": [ "l2 = [1,2,'A','B',a1]" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 in l2" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 not in l2" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a1 in l2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Identity Operator" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To check if 2 variables are the same (refer to the same object), we use the identity operator." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The identity operator is the keyword **is**. We can also use **not is**." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It evaluates to a boolean value." ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "student_1 is student_2" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 is 2 " ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'2' is \"2\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Type Casting" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Converting one type of a variable to annother is known as type casting." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For type casting, we mention the datatype name(str/ int/ float/ bool etc) and provide an argument to it, that is of another type." ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number5\n" ] } ], "source": [ "a = input(\"Enter a number\")" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(a))" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "b = int(a) #This converts the string to an integer." ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [], "source": [ "c = float(a) #This converts the string to a float." ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(b))" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(c))" ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [], "source": [ "d = str(b) #This converts the integer to a string" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n" ] } ], "source": [ "print(type(d))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## range, zip, enumerate and len" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### range()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This takes 2 forms\n", "- range(stop)\n", "- range(start, stop\\[, step])" ] }, { "cell_type": "code", "execution_count": 90, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(5):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 91, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "11\n" ] } ], "source": [ "for i in range(10,12):\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 92, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "8\n", "11\n" ] } ], "source": [ "for i in range(5,14,3):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### zip()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The purpose of zip() is to map the similar index of multiple containers so that they can be used just using as single entity. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This function takes an arbitrary number of multiple containers of the same size, and returns tuples corresponding to same indices." ] }, { "cell_type": "code", "execution_count": 93, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2 5 A\n", "3 6 10\n", "4 7 B\n" ] } ], "source": [ "for tup in zip([2,3,4],(5,6,7),{'A','B',10}):\n", " i, j, k = tup\n", " print(i,j,k)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### enumerate()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "It returns an enumerate object, which contains indices and values of all items as a tuple. It is used in the for loop, to get indices and elements one by one" ] }, { "cell_type": "code", "execution_count": 94, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 <__main__.Abc object at 0x00000228114CC198>\n", "Next\n", "1 <__main__.StudentRecord object at 0x00000228114C1198>\n", "Next\n", "2 1\n", "Next\n", "3 2\n", "Next\n", "4 A\n", "Next\n" ] } ], "source": [ "for i,j in enumerate(l1):\n", " print(i, j)\n", " print(\"Next\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thus, in for loops, we commonly use enumerate to get indices and elements one by one." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can also start the numbers generated(indices) from a number other than 0. For example," ] }, { "cell_type": "code", "execution_count": 95, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10 <__main__.Abc object at 0x00000228114CC198>\n", "11 <__main__.StudentRecord object at 0x00000228114C1198>\n", "12 1\n", "13 2\n", "14 A\n" ] } ], "source": [ "for i,j in enumerate(l1, 10):\n", " print(i,j)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### len()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This returns the length of a collectible datatype." ] }, { "cell_type": "code", "execution_count": 96, "metadata": {}, "outputs": [], "source": [ "l1 = [2,3,4,5,6,7,8]" ] }, { "cell_type": "code", "execution_count": 97, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "7\n" ] } ], "source": [ "print(len(l1))" ] }, { "cell_type": "code", "execution_count": 98, "metadata": {}, "outputs": [], "source": [ "s1 = {1,2,3,4}" ] }, { "cell_type": "code", "execution_count": 99, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4\n" ] } ], "source": [ "print(len(s1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Since we now know every datatype is nothing but a class, there should be some methods they provide as well right? Let's now go over the powerful inbuilt methods relevant to each datatype." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### format()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This allows you to use variable names in a string, which will be replaced by the value of the variable when executed." ] }, { "cell_type": "code", "execution_count": 100, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'[2, 3, 4, 5, 6, 7, 8] is a list'" ] }, "execution_count": 100, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"{} is a list\".format(l1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The curly braces are a placeholder, we have to pass a corresponding argument to the format function." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For multiple arguments, we can use positional arguments(the first curly braces will correspond to the first argument and so on), or we can use keyword arguments." ] }, { "cell_type": "code", "execution_count": 101, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'A,B is a nice idea.'" ] }, "execution_count": 101, "metadata": {}, "output_type": "execute_result" } ], "source": [ "v1 = 'A'\n", "v2 = 'B'\n", "\"{a},{b} is a nice idea.\".format(a=v1,b=v2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Python3 supports \"fstrings\". These are a more powerful way to format strings." ] }, { "cell_type": "code", "execution_count": 102, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'A,B is a nice idea.'" ] }, "execution_count": 102, "metadata": {}, "output_type": "execute_result" } ], "source": [ "f\"{v1},{v2} is a nice idea.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here, we preceed the string with an 'f', and the values in the curly braces are the variable names." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### lower(), upper()." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These are used to convert the string to lower/upper case." ] }, { "cell_type": "code", "execution_count": 103, "metadata": {}, "outputs": [], "source": [ "s1 = \"I aM a HuMaN\"" ] }, { "cell_type": "code", "execution_count": 104, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'i am a human'" ] }, "execution_count": 104, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1.lower()" ] }, { "cell_type": "code", "execution_count": 105, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I AM A HUMAN'" ] }, "execution_count": 105, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"I aM a HuMaN\".upper()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### split()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We use this to split a string based on a specific character (the default is whitespace)" ] }, { "cell_type": "code", "execution_count": 106, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['I', 'am', 'a', 'human']" ] }, "execution_count": 106, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"I am a human\".split()" ] }, { "cell_type": "code", "execution_count": 107, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['I', 'aM', 'a', 'HuMaN']" ] }, "execution_count": 107, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1.split()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "To use a custom delimiter, we have to pass an argument to the split function." ] }, { "cell_type": "code", "execution_count": 108, "metadata": {}, "outputs": [], "source": [ "s2 = \"Hey;There;I;am;Here\"" ] }, { "cell_type": "code", "execution_count": 109, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Hey;There;I;am;Here']" ] }, "execution_count": 109, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s2.split()" ] }, { "cell_type": "code", "execution_count": 110, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['Hey', 'There', 'I', 'am', 'Here']" ] }, "execution_count": 110, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s2.split(';')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### join()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The opposite of split is join. split returns a list. join takes as argument a list, and joins them with the specified string delimiter. " ] }, { "cell_type": "code", "execution_count": 111, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'I.am.here'" ] }, "execution_count": 111, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'.'.join(['I','am','here'])" ] }, { "cell_type": "code", "execution_count": 112, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'IAmHere'" ] }, "execution_count": 112, "metadata": {}, "output_type": "execute_result" } ], "source": [ "''.join(['I','Am','Here'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More string functions can be found [here](https://www.programiz.com/python-programming/methods/string)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### max(), min(), sum()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "They return the largest, smallest and sum of values in the list." ] }, { "cell_type": "code", "execution_count": 113, "metadata": {}, "outputs": [], "source": [ "l1 = [2,3,4,5,6]" ] }, { "cell_type": "code", "execution_count": 114, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 114, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sum(l1)" ] }, { "cell_type": "code", "execution_count": 115, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 115, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(l1)" ] }, { "cell_type": "code", "execution_count": 116, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 116, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min(l1)" ] }, { "cell_type": "code", "execution_count": 117, "metadata": {}, "outputs": [], "source": [ "l2 = ['a','b',2,3,4]" ] }, { "cell_type": "code", "execution_count": 118, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0msum\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ml2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ], "source": [ "sum(l2)" ] }, { "cell_type": "code", "execution_count": 119, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmin\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ml2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: '<' not supported between instances of 'int' and 'str'" ] } ], "source": [ "min(l2)" ] }, { "cell_type": "code", "execution_count": 120, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'>' not supported between instances of 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmax\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ml2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: '>' not supported between instances of 'int' and 'str'" ] } ], "source": [ "max(l2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Thus, we need to have the same datatype in the list, for these functions to work." ] }, { "cell_type": "code", "execution_count": 121, "metadata": {}, "outputs": [], "source": [ "l3 = ['a','b','z','d']" ] }, { "cell_type": "code", "execution_count": 122, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'z'" ] }, "execution_count": 122, "metadata": {}, "output_type": "execute_result" } ], "source": [ "max(l3)" ] }, { "cell_type": "code", "execution_count": 123, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'a'" ] }, "execution_count": 123, "metadata": {}, "output_type": "execute_result" } ], "source": [ "min(l3)" ] }, { "cell_type": "code", "execution_count": 124, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "unsupported operand type(s) for +: 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0msum\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ml3\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for +: 'int' and 'str'" ] } ], "source": [ "sum(l3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "sum() needs all integers." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### sorted()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This will return a sorted list(does not modify the original list)." ] }, { "cell_type": "code", "execution_count": 125, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[2, 3, 4, 5, 6]" ] }, "execution_count": 125, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(l1)" ] }, { "cell_type": "code", "execution_count": 126, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'<' not supported between instances of 'int' and 'str'", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0msorted\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ml2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mTypeError\u001b[0m: '<' not supported between instances of 'int' and 'str'" ] } ], "source": [ "sorted(l2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Again, it needs to be all integers, or all strings." ] }, { "cell_type": "code", "execution_count": 127, "metadata": {}, "outputs": [], "source": [ "l3 = ['a','b','z','d']" ] }, { "cell_type": "code", "execution_count": 128, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'd', 'z']" ] }, "execution_count": 128, "metadata": {}, "output_type": "execute_result" } ], "source": [ "sorted(l3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More List methods can be found [here](https://www.w3schools.com/python/python_ref_list.asp)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionary Functions" ] }, { "cell_type": "code", "execution_count": 129, "metadata": {}, "outputs": [], "source": [ "dict_1 = {1:0,2:1,3:'a'}" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### keys()" ] }, { "cell_type": "code", "execution_count": 130, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_keys([1, 2, 3])" ] }, "execution_count": 130, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict_1.keys()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This returns all the keys in that dictionary." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### pop()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This removes the key-value pair and returns the value with the given key." ] }, { "cell_type": "code", "execution_count": 131, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 131, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dict_1.pop(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "More Dictionary methods can be found [here](https://www.w3schools.com/python/python_ref_dictionary.asp)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# This concludes our Introduction into Python. Thank you!" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.5" } }, "nbformat": 4, "nbformat_minor": 2 }