├── Args.md ├── Beautiful_Soup.md ├── Format_Function.md ├── JSON.md ├── Lambda.md ├── Logging.md ├── RE.md ├── README.md ├── README1.md ├── Request_Module.md ├── With_As.md ├── Yield.md ├── argparse.md ├── generator.md ├── images ├── A1.png ├── A2.png ├── A3.png ├── A4.png ├── A5.png ├── A6.png ├── A7.png ├── F1.png ├── F2.png ├── F3.png ├── F4.png ├── L1.png ├── L2.png ├── L3.png ├── L4.png ├── L5.png ├── LO1.png ├── LO2.png ├── LO3.png ├── LO4.png ├── LO5.png ├── LO6.png ├── WA1.png ├── WA2.png ├── Y1.png ├── Y2.png ├── Y3.png └── Y4.png └── oopm.md /Args.md: -------------------------------------------------------------------------------- 1 | ## Args and Kwargs 2 | ```python 3 | The purpose of *args is that, *args are used to help the developer passing a variable number 4 | of arguments to a function. 5 | The symbol * makes args iterable which means that you can run a for loop and process 6 | every argument inside the args list. 7 | ``` 8 | ### Example 9 | ![Code1](/images/A1.png) 10 | ``` 11 | Now what if you want to pass a list and print every number in the list 12 | ``` 13 | ![Code2](/images/A2.png) 14 | ```python 15 | The list is getting printed in one line as the whole list is taken as 1 parameter. 16 | Suppose if you want to print each element of the list then while passing parameters in call add * before list name. 17 | ``` 18 | ![Code3](/images/A3.png) 19 | ``` 20 | **kwargs help the developer to give arbitrary keyworded arguments to a 21 | function and access them later in a dictionary. 22 | We will see an example where we are passing 2 parameters to a 23 | function with 2 parameters and to a function with kargs parameter. 24 | ``` 25 | ![Code4](/images/A4.png) 26 | ``` 27 | We can see that in the former case it is printing 1 1 so we cannot identify which is x and which is y, But in the latter case it is easily recognizable. 28 | 29 | What if we only want to print the value of x then: 30 | ``` 31 | ![Code5](/images/A5.png) 32 | ``` 33 | Now if we want to use *args and **kwargs together: 34 | First we should see to it that *args should always be before 35 | **kwargs or else it will throw an error message. 36 | ``` 37 | ![Code6](/images/A6.png) 38 | ![Code7](/images/A7.png) 39 | -------------------------------------------------------------------------------- /Beautiful_Soup.md: -------------------------------------------------------------------------------- 1 | ## Beautiful Soup 2 | ### Introduction 3 | ``` 4 | Beautiful Soup is a Python library for pulling data out of HTML and XML files.At the beginning of your Python script, import the library.Now you have to pass something to BeautifulSoup to create a soup object. That could be a document or an URL.BeautifulSoup does not fetch the web page for you, you have to do that yourself. 5 | ``` 6 | ### Filtering 7 | #### String 8 | ``` 9 | The simplest filter is a string. 10 | Pass a string to a search method and Beautiful Soup will perform a match against 11 | that exact string. 12 | ``` 13 | ```python 14 | This code finds all the 'b' tags in the document (you can replace b with any 15 | tag you want to find) 16 | 17 | soup.find_all('b') 18 | ``` 19 | #### Regular Expression 20 | ```python 21 | If you pass in a regular expression object, Beautiful Soup will filter against 22 | that regular expression using its match() method. 23 | 24 | This code finds all the tags whose names start with the letter "b", 25 | in this case, the 'body' tag and the 'b' tag: 26 | 27 | import re 28 | for tag in soup.find_all(re.compile("^b")): 29 | print(tag.name) 30 | 31 | This code finds all the tags whose names contain the letter "t": 32 | 33 | for tag in soup.find_all(re.compile("t")): 34 | print(tag.name) 35 | ``` 36 | #### List 37 | ```python 38 | If you pass in a list, Beautiful Soup will allow a string match against any 39 | item in that list. 40 | 41 | This code finds all the 'a' tags and all the 'b' tags 42 | 43 | print soup.find_all(["a", "b"]) 44 | ``` 45 | ### Example 46 | One common task is extracting all the URLs found within a page’s 'a' tags.Using the find_all method, gives us a whole list of elements with the tag "a". 47 | ```python 48 | for link in soup.find_all('a'): 49 | print(link.get('href')) 50 | ``` 51 | Another common task is extracting all the text from a page: 52 | ```python 53 | print(soup.get_text()) 54 | ``` 55 | 56 | 57 | -------------------------------------------------------------------------------- /Format_Function.md: -------------------------------------------------------------------------------- 1 | ### Format Function 2 | ```python 3 | The .format() method of the str type is an extremely convenient way to format text exactly the way you want it. 4 | Here is the general form: 5 | template.format(p0, p1, ..., k0=v0, k1=v1, ...) 6 | The arguments to the .format() method are of two types. The list starts with zero or more positional arguments pi, followed by zero or more keyword arguments of the form ki=vi, where each ki is a name with an associated value vi. 7 | ``` 8 | ### Example 9 | ``` 10 | 1.Here we could see that if there are are no values in the curly brackets it directly maps according to the position. And if there are are position given in the curly brackets then it maps them according to the given index. 11 | ``` 12 | ![Code1](/images/F1.png) 13 | ``` 14 | 2.If you want to shift a no to right then you can include the no of spaces required after the colon 15 | ``` 16 | ![Code2](/images/F2.png) 17 | ``` 18 | 3.For printing a no its square and its cube we can use the formatting techniques. 19 | ``` 20 | ![Code3](/images/F3.png) 21 | ``` 22 | We could see the difference when we use the formatting tools. The 1st one uses formatting functions. 23 | ``` 24 | ![Code4](/images/F4.png) 25 | ``` 26 | 4.We can use it for rounding of some values to given decimal points. 27 | ``` 28 | -------------------------------------------------------------------------------- /JSON.md: -------------------------------------------------------------------------------- 1 | ## JSON Module 2 | ### What is it? 3 | ``` 4 | The json library can parse JSON from strings or files. The library parses JSON into a Python dictionary or list. It can also convert Python dictionaries or lists into JSON strings. 5 | ``` 6 | ### How to use? 7 | Take the following string containing JSON data: 8 | ```python 9 | json_string = '{"first_name": "Guido", "last_name":"Rossum"}' 10 | ``` 11 | It can be parsed like this: 12 | ```python 13 | import json 14 | parsed_json = json.loads(json_string) 15 | ``` 16 | and can now be used as a normal dictionary: 17 | ```python 18 | print(parsed_json['first_name']) 19 | "Guido" 20 | ``` 21 | You can also convert the following to JSON: 22 | ```python 23 | d = { 24 | 'first_name': 'Guido', 25 | 'second_name': 'Rossum', 26 | 'titles': ['BDFL', 'Developer'], 27 | } 28 | 29 | print(json.dumps(d)) 30 | '{"first_name": "Guido", "last_name": "Rossum", "titles": ["BDFL", "Developer"]}' 31 | ``` 32 | 33 | 34 | 35 | ### Example 36 | #### Python Dictionaries to JSON Strings 37 | Code: 38 | ```python 39 | import json 40 | student = {"101":{"class":'V', "Name":'Rohit', "Roll_no":7}, 41 | "102":{"class":'V', "Name":'David', "Roll_no":8}, 42 | "103":{"class":'V', "Name":'Samiya', "Roll_no":12}} 43 | print(json.dumps(student)); 44 | ``` 45 | Output 46 | ``` 47 | {"103": {"class": "V", "Name": "Samiya", "Roll_no": 12}, 48 | "102": {"class": "V", "Name": "David", "Roll_no": 8}, 49 | "101": {"class": "V", "Name": "Rohit", "Roll_no": 7}} 50 | ``` 51 | #### JSON Strings to Python Dictionaries 52 | Code: 53 | ```python 54 | import json 55 | json_data = '{"103": {"class": "V", "Name": "Samiya", "Roll_n": 12}, "102": {"class": "V", "Name": "David", "Roll_no": 8}, "101": {"class": "V", "Name": "Rohit", "Roll_no": 7}}'; 56 | print(json.loads(json_data)); 57 | ``` 58 | Output: 59 | ``` 60 | {"103": {"class": "V", "Name": "Samiya", "Roll_no": 12}, 61 | "102": {"class": "V", "Name": "David", "Roll_no": 8}, 62 | "101": {"class": "V", "Name": "Rohit", "Roll_no": 7}} 63 | ``` 64 | 65 | -------------------------------------------------------------------------------- /Lambda.md: -------------------------------------------------------------------------------- 1 | ## Lambda 2 | ```python 3 | Lambda functions are called as anonymous functions i.e a function that is defined without a name. 4 | The general syntax of a lambda function is quite simple: 5 | lambda argument_list: expression 6 | Lambda is a tool for building functions, or more precisely, for building function objects. 7 | That means that Python has two tools for building functions: 8 | def and lambda. 9 | Def: 10 | ``` 11 | ![Code1](/images/L1.png) 12 | ```python 13 | Lambda: 14 | ``` 15 | ![Code2](/images/L2.png) 16 | ```python 17 | Generally, functions are created for to reduce code duplication, or to modularize code. 18 | But suppose you need to create a function that is going to be used only once. 19 | Well, first of all, you don’t need to give the function a name. 20 | It can be “anonymous”. And you can just define it right in the place where you want to use it. 21 | That’s where lambda is useful. 22 | Lambda functions are mainly used in combination with the functions filter(), map() and reduce(). 23 | ``` 24 | ### With Map 25 | ```python 26 | r = map(func, seq) 27 | The first argument func is the name of a function and the second a sequence (e.g. a list) seq. map() applies the function func to all the elements of the sequence seq. 28 | It returns a new list with the elements changed by func. 29 | Here is an example where using lambda with map reduces the size of code which was earlier written by normal functions. 30 | ``` 31 | ![Code3](/images/L3.png) 32 | ![Code4](/images/L4.png) 33 | ### With FILTER() 34 | ```pyhton 35 | The function filter(function, list) offers an elegant way to filter out all the elements of a list, for which the function function returns True. 36 | ``` 37 | ![Code5](/images/L5.png) 38 | -------------------------------------------------------------------------------- /Logging.md: -------------------------------------------------------------------------------- 1 | ## Logging 2 | ```python 3 | When you transfer money, there are transfer records. 4 | If something goes wrong, people can read the log and has a chance to figure out what happened. 5 | Likewise, logging is important for system developing, debugging and running. 6 | When a program crashes, if there is no logging record, you have little chance to understand what happened. 7 | You can use the logging functions by just importing logging. 8 | ``` 9 | ### Logging Levels 10 | ``` 11 | There are many logging levels. 12 | The numeric values of logging levels are given in the following table. 13 | These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. 14 | If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost. 15 | ``` 16 | |Level| Numeric value| 17 | |-----|------| 18 | CRITICAL|50 19 | ERROR|40 20 | WARNING|30 21 | INFO|20 22 | DEBUG|10 23 | NOTSET|0 24 | ```python 25 | They are usually used with: 26 | logging.basciConfig(level=logging.DEBUG) Or 27 | logging.basciConfig(level=logging.INFO) 28 | ``` 29 | ### Steps 30 | ```python 31 | Create a file and enter the logging code and then run the code , output will appear on the shell. 32 | If you are using any file name like: 33 | logging.basicConfig(filename='example.log',level=logging.DEBUG) 34 | Then you can see your output in the file named ‘example’ . 35 | However the default level is WARNING 36 | ``` 37 | #### Case 1 38 | ```python 39 | If no level was mentioned: 40 | It does not take the .info information 41 | ``` 42 | ![Code1](/images/LO1.png) 43 | ![Code2](/images/LO2.png) 44 | #### Case 2 45 | ```python 46 | When level was debug, all the statements were executed. 47 | ``` 48 | ![Code3](/images/LO3.png) 49 | ![Code4](/images/LO4.png) 50 | ```python 51 | Here we can see that logging is similar to print statements 52 | But.. 53 | It works when the program is a simple script, but for complex systems, you better not to use this approach. First of all, you cannot leave only important messages in the log, you may see a lots of garbage messages in the log, but can’t find anything useful.You also cannot control those print statements without modifying code, you may forgot to remove those unused prints. 54 | 55 | It can be used with some formatting functions also: 56 | ``` 57 | ![Code5](/images/LO5.png) 58 | ![Code6](/images/LO6.png) 59 | 60 | -------------------------------------------------------------------------------- /RE.md: -------------------------------------------------------------------------------- 1 | ## Regular Expresion 2 | ### What is it? 3 | ``` 4 | A regular expression is a special sequence of characters that helps you match or find other strings or sets of strings, using a specialized syntax held in a pattern. 5 | 6 | There are various characters, which would have special meaning when they are used in regular expression. To avoid any confusion while dealing with regular expressions, we would use Raw Strings as r'expression'. 7 | ``` 8 | ### Match Function 9 | ``` 10 | This function attempts to match RE pattern to string with optional flags. 11 | Here is the syntax for this function − 12 | ``` 13 | ```python 14 | re.match(pattern, string, flags=0) 15 | ``` 16 | ``` 17 | Here is the description of the parameters: 18 | ``` 19 | |Parameter | Description | 20 | | ------ | ------ | 21 | |pattern| This is the regular expression to be matched.| 22 | |string| This is the string, which would be searched to match the pattern at the beginning of string.| 23 | |flags| You can specify different flags using bitwise OR. These are modifiers, which are listed in the table below.| 24 | #### Example 25 | ```python 26 | #!/usr/bin/python 27 | import re 28 | 29 | line = "Cats are smarter than dogs" 30 | 31 | matchObj = re.match( r'(.*) are (.*?) .*', line, re.M|re.I) 32 | 33 | if matchObj: 34 | print "matchObj.group() : ", matchObj.group() 35 | print "matchObj.group(1) : ", matchObj.group(1) 36 | print "matchObj.group(2) : ", matchObj.group(2) 37 | else: 38 | print "No match!!" 39 | ``` 40 | The result obtained will be:- 41 | ``` python 42 | matchObj.group() : Cats are smarter than dogs 43 | matchObj.group(1) : Cats 44 | matchObj.group(2) : smarter 45 | ``` 46 | ### Match Function 47 | ``` 48 | This function searches for first occurrence of RE pattern within string with optional flags. 49 | Here is the syntax for this function: 50 | ``` 51 | ```python 52 | re.search(pattern, string, flags=0) 53 | ``` 54 | The re.search function returns a match object on success, none on failure. We use group(num) or groups() function of match object to get matched expression. 55 | |Match Object Methods | Description | 56 | | ------ | ------ | 57 | group(num=0)| This method returns entire match (or specific subgroup num) 58 | groups()| This method returns all matching subgroups in a tuple (empty if there weren't any) 59 | 60 | #### Example 61 | ```python 62 | #!/usr/bin/python 63 | import re 64 | 65 | line = "Cats are smarter than dogs"; 66 | 67 | searchObj = re.search( r'(.*) are (.*?) .*', line, re.M|re.I) 68 | 69 | if searchObj: 70 | print "searchObj.group() : ", searchObj.group() 71 | print "searchObj.group(1) : ", searchObj.group(1) 72 | print "searchObj.group(2) : ", searchObj.group(2) 73 | else: 74 | print "Nothing found!!" 75 | ``` 76 | Output: 77 | ```python 78 | searchObj.group() : Cats are smarter than dogs 79 | searchObj.group(1) : Cats 80 | searchObj.group(2) : smarter 81 | ``` 82 | ### Match vs Search 83 | ``` 84 | match checks for a match only at the beginning of the string, while search checks for a match anywhere in the string. 85 | ``` 86 | #### Example 87 | ```python 88 | #!/usr/bin/python 89 | import re 90 | 91 | line = "Cats are smarter than dogs"; 92 | 93 | matchObj = re.match( r'dogs', line, re.M|re.I) 94 | if matchObj: 95 | print "match --> matchObj.group() : ", matchObj.group() 96 | else: 97 | print "No match!!" 98 | 99 | searchObj = re.search( r'dogs', line, re.M|re.I) 100 | if searchObj: 101 | print "search --> searchObj.group() : ", searchObj.group() 102 | else: 103 | print "Nothing found!!" 104 | ``` 105 | Output: 106 | ```python 107 | No match!! 108 | search --> matchObj.group() : dogs 109 | ``` 110 | ### Search and Replace 111 | ```python 112 | re.sub(pattern, repl, string, max=0) 113 | This method replaces all occurrences of the RE pattern in string with repl, substituting all occurrences unless max provided. This method returns modified string. 114 | ``` 115 | #### Example 116 | ```python 117 | #!/usr/bin/python 118 | import re 119 | 120 | phone = "2004-959-559 # This is Phone Number" 121 | 122 | # Delete Python-style comments 123 | num = re.sub(r'#.*$', "", phone) 124 | print "Phone Num : ", num 125 | 126 | # Remove anything other than digits 127 | num = re.sub(r'\D', "", phone) 128 | print "Phone Num : ", num 129 | ``` 130 | Output: 131 | ```python 132 | Phone Num : 2004-959-559 133 | Phone Num : 2004959559 134 | ``` 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Advance Python Notes 2 | 3 | ### Content 4 | 5 | 1. [In-build and Custom Generators](./generator.md) 6 | 2. [Modules in Python]() 7 | 1. [Argeparse Module](./argparse.md) 8 | 2. [Request Module](./Request_Module.md) 9 | 3. [JSON module](./JSON.md) 10 | 4. [Regular expression (re) module](./RE.md) 11 | 5. [BeautifulSoup](./Beautiful_Soup.md) 12 | 3. [Decorators in Python]() 13 | 5. [Usefull functions]() 14 | 1. [Enumerate]() 15 | 2. [zip]() 16 | 3. [map]() 17 | 4. [reduce]() 18 | 6. [Muliprocessing or Multi threading]() 19 | 7. [Object Oriented Programming]() 20 | 1. [ \__init__ (Constructor) ]() 21 | 2. [Inheritance]() 22 | 1. [Introduction]() 23 | 2. [Super Method]() 24 | 3. [Operator Overloading]() 25 | 4. [Special Methods]() 26 | 1. [dir method]() 27 | 2. [\__next__]() 28 | 3. [\__iter__]() 29 | 4. [\__str__]() 30 | 5. [\__repr__]() 31 | 8. [Miscellaneous Features]() 32 | 1. [with as](./With_As.md) 33 | 2. [yield](./Yield.md) 34 | 3. [lambda](./Lambda.md) 35 | 4. [.format function](./Format_Function.md) 36 | 5. [ logging in python](./Logging.md) 37 | 6. [args and kwargs](./Args.md) 38 | -------------------------------------------------------------------------------- /README1.md: -------------------------------------------------------------------------------- 1 | # Advance Python Notes 2 | 3 | ### Content 4 | 5 | 1. [In-build and Custom Generators](./generator.md) 6 | 2. [Modules in Python]() 7 | 1. [Argeparse Module]() 8 | 2. [Request Module]() 9 | 3. [JSON module]() 10 | 4. [Regular expression (re) module]() 11 | 5. [BeautifulSoup]() 12 | 3. [Decorators in Python]() 13 | 5. [Usefull functions]() 14 | 1. [Enumerate]() 15 | 2. [zip]() 16 | 3. [map]() 17 | 4. [reduce]() 18 | 6. [Muliprocessing or Multi threading]() 19 | 7. [Object Oriented Programming](./oopm.md) 20 | 1. [ \__init__ (Constructor) ](./oopm.md/#the-init-method) 21 | 2. [Inheritance](./oopm.md/#inheritance) 22 | 1. [Introduction]() 23 | 2. [Super Method]() 24 | 3. [Operator Overloading](./oopm.md/#operator-overloading) 25 | 4. [Special Methods](./oopm.md/#special-methods) 26 | 1. [dir method]() 27 | 2. [\__next__]() 28 | 3. [\__iter__]() 29 | 4. [\__str__]() 30 | 5. [\__repr__]() 31 | 8. [Miscellaneous Features]() 32 | 1. [with as]() 33 | 2. [yield]() 34 | 3. [lambda]() 35 | 4. [.format function]() 36 | 5. [ logging in python]() 37 | 6. [args and kwargs]() 38 | -------------------------------------------------------------------------------- /Request_Module.md: -------------------------------------------------------------------------------- 1 | ## Request Module 2 | ### Introduction 3 | ``` 4 | Requests will allow you to send HTTP/1.1 requests using Python. With it, you can add content like headers, form data, multipart files, and parameters via simple Python libraries. It also allows you to access the response data of Python in the same way. 5 | ``` 6 | ### Make a GET request 7 | ```python 8 | import requests 9 | URL = "http://maps.googleapis.com/maps/api/geocode/json" 10 | location = "delhi technological university" 11 | PARAMS = {'address':location} 12 | r = requests.get(url = URL, params = PARAMS) 13 | data = r.json() 14 | latitude = data['results'][0]['geometry']['location']['lat'] 15 | longitude = data['results'][0]['geometry']['location']['lng'] 16 | formatted_address = data['results'][0]['formatted_address'] 17 | print("Latitude:%s\nLongitude:%s\nFormatted Address:%s" 18 | %(latitude, longitude,formatted_address)) 19 | ``` 20 | Output: 21 | ``` 22 | Latitude:28.7499867 23 | Longitude:77.1183137 24 | Formatted Address:Delhi Technological University, Shahbad Daulatpur Village, Rohini, Delhi, 110042, India 25 | ``` 26 | ### Make a POST request 27 | ```python 28 | import requests 29 | API_ENDPOINT = "http://pastebin.com/api/api_post.php" 30 | API_KEY = "XXXXXXXXXXXXXXXXX" 31 | source_code = ''' 32 | print("Hello, world!") 33 | a = 1 34 | b = 2 35 | print(a + b) 36 | ''' 37 | data = {'api_dev_key':API_KEY, 38 | 'api_option':'paste', 39 | 'api_paste_code':source_code, 40 | 'api_paste_format':'python'} 41 | 42 | r = requests.post(url = API_ENDPOINT, data = data) 43 | pastebin_url = r.text 44 | print("The pastebin URL is:%s"%pastebin_url) 45 | ``` 46 | Output: 47 | ```python 48 | This example explains how to paste your source_code to pastebin.com by sending POST request to the PASTEBIN API.You will need to generate an API key here http://pastebin.com/signup 49 | data = {'api_dev_key':API_KEY, 50 | 'api_option':'paste', 51 | 'api_paste_code':source_code, 52 | 'api_paste_format':'python'} 53 | Here again, we will need to pass some data to API server. We store this data as a dictionary. 54 | r = requests.post(url = API_ENDPOINT, data = data) 55 | Here we create a response object ‘r’ which will store the request-response. We use requests.post() method since we are sending a POST request. The two arguments we pass are url and the data dictionary. 56 | pastebin_url = r.text 57 | In response, the server processes the data sent to it and sends the pastebin URL of your source_code which can be simply accessed by r.text . 58 | ``` 59 | 60 | -------------------------------------------------------------------------------- /With_As.md: -------------------------------------------------------------------------------- 1 | ## With As 2 | ```python 3 | With the "With" statement, you get better syntax and exceptions handling. 4 | The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks. 5 | In addition, it will automatically close the file. 6 | The with statement provides a way for ensuring that a clean-up is always used. 7 | The lines after as can be used as an object to refer that.Without the with statement, 8 | we would write something like this: 9 | 10 | file = open("hello.txt") 11 | data = file.read() 12 | print data 13 | file.close() # It's important to close the file when you're done with it 14 | 15 | With Statement Usage 16 | Opening a file using with is as simple as: 17 | 18 | with open(filename) as file: 19 | with open("hello.txt") as inFile: # Use file to refer to the file object 20 | data = inFile.read() 21 | print data 22 | 23 | Here we did not write separate close statement as it is handled by with. 24 | ``` 25 | ![Output](/images/WA1.png) 26 | ``` 27 | Above is the file hello.txt 28 | ``` 29 | ![Code](/images/WA2.png) 30 | ```python 31 | Thus we can see that when we use “with” statement there is no need of separate close statement. 32 | With more than one item, the context managers are processed as if multiple with statements were nested: 33 | with A() as a, B() as b: 34 | suite 35 | is equivalent to 36 | with A() as a: 37 | with B() as b: 38 | suite 39 | ``` 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /Yield.md: -------------------------------------------------------------------------------- 1 | ## Yield 2 | ```python 3 | When we call a function in Python, the function will normally start working until it encounters a return, exception, 4 | or reaches its end – after which it returns control back to the caller. 5 | Whenever you call that function again, the process will start from scratch! 6 | Whereas in case of the yield statement, it suspends function’s execution and sends a value back to calle, 7 | but retains enough state to enable function to resume where it is left off. 8 | When resumed, the function continues execution immediately after the last yield run. 9 | This allows its code to produce a series of values over time, rather them computing them at once and sending them back like a list. 10 | ``` 11 | ![Code1](/images/Y1.png) 12 | ```python 13 | Here we can’t return 2 values at a time.Using yield, it is allowed. 14 | ``` 15 | ![Code2](/images/Y2.png) 16 | ```python 17 | Yield are used in Python generators. A generator function is defined like a normal function, but whenever it needs to generate a value, it does so with the yield keyword rather than return. If the body of a def contains yield, the function automatically becomes a generator function. 18 | ``` 19 | ![Code3](/images/Y3.png) 20 | ```python 21 | Or it could be like this: 22 | ``` 23 | ![Code4](/images/Y4.png) 24 | 25 | -------------------------------------------------------------------------------- /argparse.md: -------------------------------------------------------------------------------- 1 | ## Argparse 2 | ### What is it? 3 | ``` 4 | Parser for command-line options, arguments and subcommands.The argparse module makes it easy to write user-friendly command-line interfaces. 5 | 6 | When you run the "ls" command without any options, it will default displaying the 7 | contents of the current directory 8 | 9 | If you run "ls" on a different directory that you currently are in, you would type 10 | "ls directory_name". The "directory_name" is a "positional argument", which means 11 | that the program know what to do with the value. 12 | 13 | To get more information about a file we can use the "-l" switch. 14 | 15 | The "-l" is knowns as an "optional argument" 16 | 17 | If you want to display the help text of the ls command, you would type "ls --help" 18 | ``` 19 | ### How to use? 20 | We need to import the following: 21 | ```python 22 | import argparse 23 | parser = argparse.ArgumentParser() 24 | parser.parse_args() 25 | ``` 26 | Even without the arguements being specified, executing this code with '--help' option gives us the only pre-coded messgae available. 27 | ```python 28 | python program.py --help (or python program.py -h) 29 | usage: program.py [-h] 30 | 31 | optional arguments: 32 | -h, --help show this help message and exit 33 | ``` 34 | 35 | ### Example 36 | ```python 37 | import argparse 38 | import sys 39 | 40 | def main(): 41 | parser = argparse.ArgumentParser() 42 | parser.add_argument('--x', type=float, default=1.0, 43 | help='What is the first number?') 44 | parser.add_argument('--y', type=float, default=1.0, 45 | help='What is the second number?') 46 | parser.add_argument('--operation', type=str, default='add', 47 | help='What operation? Can choose add, sub, mul, or div') 48 | args = parser.parse_args() 49 | sys.stdout.write(str(calc(args))) 50 | 51 | def calc(args): 52 | if args.operation == 'add': 53 | return args.x + args.y 54 | elif args.operation == 'sub': 55 | return args.x - args.y 56 | elif args.operation == 'mul': 57 | return args.x * args.y 58 | elif args.operation == 'div': 59 | return args.x / args.y 60 | 61 | if __name__ == '__main__': 62 | main() 63 | ``` 64 | Now if we pass values for x and y and also specify the operation, we get the desired results 65 | ```python 66 | python argparse_example.py --x=5 --y=3 --operation=mul 67 | 15.0 68 | ``` 69 | Instead, if we invoke the help option, we get 70 | ```python 71 | python argparse_example.py -h 72 | usage: argparse_example.py [-h] [--x X] [--y Y] [--operation OPERATION] 73 | 74 | optional arguments: 75 | -h, --help show this help message and exit 76 | --x X What is the first number? 77 | --y Y What is the second number? 78 | --operation OPERATION 79 | What operation? Can choose add, sub, mul, or div 80 | ``` 81 | 82 | -------------------------------------------------------------------------------- /generator.md: -------------------------------------------------------------------------------- 1 | ## In-Build Generators: 2 | A generator is a function that generates output whenever you call it and remembers the current state untill the next call is made 3 | 4 | A simple example of a generator is ```range()``` function in python 5 | 6 | ```python 7 | # this code will freeze you pc if it generates the entire list 8 | # and saves it to memory 9 | #but it doesn't 10 | range(90000000000000000000000000) 11 | ``` 12 | The reason is this creates a generator which calculates next element every time you call it 13 | 14 | ### Use of in-build generators 15 | To create a generator we have to write our expression inside parenthesis '()'. 16 | ```python 17 | n = 10 18 | # this creates a generator that gives even i upto n 19 | gen = (i for i in range(n) if i%2 == 0) 20 | for i in gen: 21 | print(i) 22 | 23 | # this creates a list that contains even i upto n 24 | # as this creates the entire list at once it's not a generators 25 | # you can call it one line for-loops 26 | # also known as list comprehensions 27 | l = [i for i in range(n) if i%2 == 0] 28 | ``` 29 | 30 | ## Custom Generators. 31 | 32 | To create more powerfull generators you can use this technique 33 | 34 | __Program to calculate fibonacci__ 35 | ```python 36 | # normal method 37 | def fibo(n): 38 | f0 = 0 39 | print(0) 40 | f1 = 1 41 | print(1) 42 | for i in range(n-2): 43 | temp = f1 44 | f1 = f1+f0 45 | f0 = temp 46 | print(f1) 47 | 48 | # generator method 49 | def fibo(n): 50 | f0 = 0 51 | yield f0 52 | f1 = 1 53 | yield f1 54 | for i in range(n-2): 55 | temp = f1 56 | f1 = f1+f0 57 | f0 = temp 58 | yield f1 59 | 60 | ``` 61 | ### Important points 62 | 1. Generators consume more time but are memory efficient and do not blow up your ram by calculating everything before hand. 63 | 2. Normal method is faster but consumes more ram memory. 64 | -------------------------------------------------------------------------------- /images/A1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A1.png -------------------------------------------------------------------------------- /images/A2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A2.png -------------------------------------------------------------------------------- /images/A3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A3.png -------------------------------------------------------------------------------- /images/A4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A4.png -------------------------------------------------------------------------------- /images/A5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A5.png -------------------------------------------------------------------------------- /images/A6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A6.png -------------------------------------------------------------------------------- /images/A7.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/A7.png -------------------------------------------------------------------------------- /images/F1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/F1.png -------------------------------------------------------------------------------- /images/F2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/F2.png -------------------------------------------------------------------------------- /images/F3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/F3.png -------------------------------------------------------------------------------- /images/F4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/F4.png -------------------------------------------------------------------------------- /images/L1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/L1.png -------------------------------------------------------------------------------- /images/L2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/L2.png -------------------------------------------------------------------------------- /images/L3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/L3.png -------------------------------------------------------------------------------- /images/L4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/L4.png -------------------------------------------------------------------------------- /images/L5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/L5.png -------------------------------------------------------------------------------- /images/LO1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/LO1.png -------------------------------------------------------------------------------- /images/LO2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/LO2.png -------------------------------------------------------------------------------- /images/LO3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/LO3.png -------------------------------------------------------------------------------- /images/LO4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/LO4.png -------------------------------------------------------------------------------- /images/LO5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/LO5.png -------------------------------------------------------------------------------- /images/LO6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/LO6.png -------------------------------------------------------------------------------- /images/WA1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/WA1.png -------------------------------------------------------------------------------- /images/WA2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/WA2.png -------------------------------------------------------------------------------- /images/Y1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/Y1.png -------------------------------------------------------------------------------- /images/Y2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/Y2.png -------------------------------------------------------------------------------- /images/Y3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/Y3.png -------------------------------------------------------------------------------- /images/Y4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/kjsce-codecell/Advance-Python-Notes/72d33bcd9b8f82e2b7bb768eca6fd17d571d0baa/images/Y4.png -------------------------------------------------------------------------------- /oopm.md: -------------------------------------------------------------------------------- 1 | ## Object Oriented Programming Methodology 2 | 3 | ### Class 4 | 5 | A class is a user-defined data type. Its a collection of 6 | objects, where objects can represent just about anything 7 | from integers to real world objects like a ball. Structure of Classes 8 | in python are very similar to that of c++ or java. 9 | 10 | For example: 11 | 12 | ```python 13 | class world: 14 | def hello(self): 15 | print("Hello World!") 16 | 17 | obj=world() 18 | obj.hello() 19 | ``` 20 | 21 | Output: 22 | ``` 23 | Hello World! 24 | ``` 25 | As we can see above, we create a class using the keyword class and the name of the class. 26 | This is followed by an indented block of statements which forms the body of the class. 27 | The body can contain methods and variables pertaining to the class. In the above example 28 | we have created a class "world" which defines a method "hello" to print the 29 | statement "Hello World!". 30 | We create an object of this class, which can access the data members and methods of the class 31 | and call the methods of the class by using the "." operator just like in c++. 32 | 33 | #### Note: 34 | ``` 35 | 1. The class methods in python need to have an extra parameter called self. This does not 36 | have a value, when a method is called. 37 | 2. If we have a method with no parameters, in the class we must have one argument that is 38 | the self argument. See hello() method in the above example. 39 | 3. This is similar to this pointer in c++ or this reference in Java. 40 | 4. When we call a method MyClass.method(arg1,arg2) this is automatically converted 41 | by python into MyClass.method(object,arg1,arg2) where object is the self parameter. 42 | ``` 43 | 44 | ### The __init__ method 45 | 46 | The __init__ method in python is similar to constructors in java or c++. 47 | That means it is run as soon as an object of the class is instantiated. 48 | This method is useful to initialize your objects in the class, before 49 | proceed further method calls. 50 | 51 | For example: 52 | ```python 53 | class name: 54 | def __init__(self,str): 55 | self.str=str 56 | 57 | def greet(self): 58 | print('Hi, my name is ',self.str) 59 | 60 | p=name('Vinitra') 61 | p.greet() 62 | ``` 63 | Output: 64 | ``` 65 | Hi, my name is Vinitra 66 | ``` 67 | ### Inheritance 68 | 69 | #### 1. Introduction 70 | 71 | Inheritance is one of the most powerful concepts of object oriented programming. 72 | It is the mechanism of deriving features of one class from another class facilitating 73 | code reusability. 74 | It constitutes defining a new class which is similar or identical to a class that 75 | already exists. The new class is hence called derived class or child class and the one 76 | from which it is inherited is called the base class or the parent class. 77 | 78 | For example: 79 | ```python 80 | class side: 81 | def __init__(self,l,b): 82 | self.l=l 83 | self.b=b 84 | 85 | class area(side): 86 | 87 | def __init__(self,l,b): 88 | side.__init__(self,l,b) 89 | 90 | def Area(self): 91 | print('Area of the rectange is ',self.l*self.b) 92 | 93 | a=area(4,5) 94 | a.Area() 95 | ``` 96 | Output: 97 | ``` 98 | Area of the rectangle is 20 99 | ``` 100 | #### 2. Super Method 101 | 102 | ```super()``` method is used to access data members and functions of parent class. 103 | The example given in the example for inheritance can also be executed by the 104 | ```super()``` method. 105 | 106 | For example: 107 | ```python 108 | class side: 109 | def __init__(self,l,b): 110 | self.l=l 111 | self.b=b 112 | 113 | class area(side): 114 | 115 | def __init__(self,l,b): 116 | super(area,self).__init__(l,b) 117 | 118 | def Area(self): 119 | print('Area of the rectange is ',self.l*self.b) 120 | 121 | a=area(4,5) 122 | a.Area() 123 | ``` 124 | Output: 125 | ``` 126 | Area of the rectangle is 20 127 | ``` 128 | ### Operator Overloading 129 | 130 | Python operators work for built-in classes. But the same operators can be made to behave 131 | in a user-defined way. For example, the + operator adds the primitive variables of 132 | primitive data types. But by operator overloading you can make the + operator to 133 | add two complex numbers! 134 | This feature that allows operators to have to different functions according to context 135 | is called Operator Overloading. 136 | See the example below to see how to overload operators. 137 | Example: 138 | ```python 139 | class Point: 140 | def __init__(self,x,y): 141 | self.x=x 142 | self.y=y 143 | 144 | def __str__(self): 145 | return "({0},{1})",format(self.x,self.y) 146 | 147 | def __add__(self,other): 148 | x=self.x+other.x 149 | y=self.y+other.y 150 | print() 151 | 152 | p1=Point(2,4) 153 | p2=Point(-1,5) 154 | print(p1+p2) 155 | ``` 156 | Output: 157 | ``` 158 | (1,9) 159 | ``` 160 | What happens is that, when you write p1+p2, python will call p1.__add__(p2) which in 161 | turn is Point.__add__(p1,p2). Also in the above example, __str__ is special function 162 | like the __init__ method i.e it gets called whenever the class is instantiated. 163 | This method is used to control the output format 164 | 165 | ### Special Methods 166 | 167 | Special functions are those methods which get executed as soon as the class is 168 | instantiated. For example: the __init__ method. 169 | There are many useful special functions in python. Given below are some of them. 170 | 171 | 1. __iter__: This method returns the iterator object and is implicitly called 172 | at the start of loops. 173 | 2. __next__: This method returns the next value and is implicity called at 174 | each loop increment. 175 | 176 | Example: 177 | ```python 178 | class Counter: 179 | def __init__(self, low, high): 180 | self.current = low 181 | self.high = high 182 | 183 | def __iter__(self): 184 | return self 185 | 186 | def __next__(self): # Python 2: def next(self) 187 | if self.current > self.high: 188 | raise StopIteration 189 | else: 190 | self.current += 1 191 | return self.current - 1 192 | 193 | for c in Counter(3, 8): 194 | print(c) 195 | ``` 196 | Output: 197 | ``` 198 | 3 199 | 4 200 | 5 201 | 6 202 | 7 203 | 8 204 | ``` 205 | 206 | 3. __str__ & __repr__: Both the functions are similar, i.e both are used to "represent" 207 | an object in a string. __repr__ gives you an official representation while __str gives 208 | informal representation. str() is used for creating output for end user while repr() 209 | is mainly used for debugging and development. Main goal of repr() is to be 210 | unambiguous and that of str() is to be readable. For example if we suspect a float 211 | has a small rounding error, repr will show us while str may not. 212 | For example: 213 | ```python 214 | x=1 215 | print(repr(x)) 216 | print(str(x)) 217 | y='string' 218 | print(repr(y)) 219 | print(str(y)) 220 | ``` 221 | Output: 222 | ``` 223 | 1 224 | 1 225 | 'string' 226 | string 227 | ``` 228 | In the above example, the return of repr() and str() are identical for int x, but not for 229 | string y. Therefore the default implementation of __repr__ for a str object can be called as 230 | an argument to eval and the return value would be a valid str object. 231 | Look at another example here: 232 | ```python 233 | class Complex: 234 | 235 | def __init__(self, real, imag): 236 | self.real = real 237 | self.imag = imag 238 | 239 | # For call to repr(). Prints object information 240 | def __repr__(self): 241 | return '%s + i%s' % (self.real, self.imag) 242 | 243 | # For call to str(). Prints readable form 244 | def __str__(self): 245 | return '%s + i%s' % (self.real, self.imag) 246 | 247 | 248 | t = Complex(10, 20) 249 | 250 | print str(t) 251 | print(t) 252 | print repr(t) 253 | ``` 254 | Output: 255 | ``` 256 | 10 + i20 257 | 10 + i20 258 | Rational(10,20) 259 | ``` 260 | You can redefine __str__ and __repr__ to suit you needs as done in the above 261 | example. 262 | 263 | 4. dir(): This method takes only 1 object as a parameter and returns a list of 264 | attributes of the object. 265 | For example: 266 | ```python 267 | class num: 268 | def __init__(self): 269 | return [1,2,3] 270 | 271 | n=num() 272 | print(dir(n)) 273 | ``` 274 | Output: 275 | ``` 276 | [1,2,3] 277 | ``` 278 | 279 | 280 | --------------------------------------------------------------------------------