{"id":21205,"date":"2022-01-20T12:26:17","date_gmt":"2022-01-20T11:26:17","guid":{"rendered":"https:\/\/firmbee.com\/?p=21205"},"modified":"2022-07-12T14:24:16","modified_gmt":"2022-07-12T12:24:16","slug":"advanced-functions-in-python","status":"publish","type":"post","link":"https:\/\/firmbee.com\/advanced-functions-in-python","title":{"rendered":"Advanced functions in Python. Part 8 Python Course from Beginner to Advanced in 11 blog posts"},"content":{"rendered":"<p><strong>This article will help the reader continue from the previous Python functions blog along with some basic applications in the real world. We will be using Visual Studio Code as our code editor. If you have not installed Visual Studio Code, the instructions are given in the <a href=\"https:\/\/firmbee.com\/part-1-python-course-in-10-blog-posts\/\">first blog.<\/a><\/strong><\/p>\r\n\r\n\r\n\r\n<h2>Advanced functions in Python &#8211; table of contents:<\/h2>\r\n<ol>\r\n<li><a href=\"#firstparagraph\">Passing functions to other functions<\/a><\/li>\r\n<li><a href=\"#secondparagraph\">Using functions inside a function<\/a><\/li>F<\r\n<li><a href=\"#thirdparagraph\">*Args in Python<\/a><\/li>\r\n<li><a href=\"#fourthparagraph\">\u201c*\u201d operator in Python<\/a><\/li>\r\n<li><a href=\"#fifthparagraph\">**kwargs in Python<\/a><\/li>\r\n<\/ol>\r\n\r\n\r\n<h2 id=\"firstparagraph\">Passing functions to other functions<\/h2>\r\n<p>As discussed in the previous blog, functions in Python are treated as objects. So like objects in Python, functions can also be passed as an argument to another function.<\/p>\r\n\r\n\r\n<p>For Example:<\/p>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndef mul(x, y):\r\n    return x*y\r\n \r\n \r\ndef add(mul, y):\r\n    return mul+y\r\n \r\n \r\nx = add(mul(9, 10), 10)\r\nprint(x)\r\n\r\n<\/pre>\r\n\r\n<p>In the above code block, it can be seen that the mul function is passed as an argument to the add function and it is stored in the x variable which is then printed to verify the answer.<\/p>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n100\r\n<\/pre>\r\n\r\n\r\n\r\n<h2 id=\"secondparagraph\">Using functions inside a function<\/h2>\r\n<p>In Python, we can define a function inside another function. These functions are called as nested functions. But in this use case, the inside function or nested function cannot be called separately. Both the examples are illustrated in the following code block.<\/p>\r\n<p>Let\u2019s write our first function.<\/p>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndef mul(x, y):\r\n \r\n    m = x*y\r\n \r\n    def square(m):\r\n        return m*m\r\n \r\n    return square(m)\r\n \r\n \r\nx = mul(9, 10)\r\n \r\nprint(x)\r\n<\/pre>\r\n \r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\n8100\r\n<\/pre>\r\n\r\n<p>In the above code block the outer function is \u201cmul\u201d which returns the function square which takes an argument \u201cm\u201d which is the multiplication of two arguments given to \u201cmul\u201d function. The code execution first starts with calling \u201cmul\u201d function, then the product of \u201cx\u201d and \u201cy\u201d gets stored in \u201cm\u201d variable. As this function is returning square function, the \u201csquare\u201d function is called and the final product which is the square of \u201cm\u201d is returned.<\/p>\r\n\r\n<p>Let\u2019s learn few important things in Python, which will make your coding journey with Python much better.<\/p>\r\n\r\n<h2 id=\"thirdparagraph\">*Args in Python<\/h2>\r\n<p>These are the arguments which we use as function parameters. Let\u2019s write a usual function using what we learned till now. We will be writing a function that can give us maximum area of a rectangle given 2 rectangle areas as parameters to the function.<\/p>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndef maxarea(a, b):\r\n    if a &gt; b:\r\n        return f'rectangle a has the more area which is {a}'\r\n    else:\r\n        return f'rectangle a has the more area which is {b}'\r\n \r\n \r\nx = maxarea(100, 60)\r\nprint(x)\r\n \r\n<\/pre>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\nrectangle a has the more area which is 100\r\n&#x5B;code lang=&quot;js&quot;]\r\n<\/pre>\r\n\r\n\r\n<p>This function is good for 2 parameters or arguments, but what if we need to compare more than 2 areas. One approach would be passing a list of areas into the function.<\/p>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndef maxarea(lis):\r\n \r\n    max = 0\r\n    for i in lis:\r\n        if i &gt; max:\r\n            max = i\r\n \r\n    return f&quot;rectangle which has the more area is {max}&quot;\r\n \r\n \r\nx = maxarea(&#x5B;100, 60, 50])\r\nprint(x)\r\n<\/pre>\r\n\r\n\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\nrectangle which has the more area is 100\r\n<\/pre>\r\n\r\n\r\n\r\n<p>This approach is good, but we should know the number of parameters or arguments to give beforehand. In  real-time code execution this would be a hassle. Hence to make the programmer\u2019s life easy, <a href=\"https:\/\/pl.wikipedia.org\/wiki\/Python\" target=\"_blank\" rel=\"noopener\">Python <\/a>uses *args and **kwargs.<\/p>\r\n\r\n\r\n<h2 id=\"fourthparagraph\">\u201c*\u201d operator in Python<\/h2>\r\n<p>This operator is an unpacking operator which is usually used to pass an unspecified number of parameters or arguments.<\/p>\r\n\r\n<h4>Unpacking arguments into tuple using * operator<\/h4>\r\n<p>As we have seen, that \u201c*\u201d operator is used for unpacking values. The example is illustrated below.<\/p>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\n\r\nx = &#x5B;1, 2, 3, 4]\r\ny = &#x5B;5, 6, 7, 8]\r\n \r\nz = *x, *y\r\n \r\nprint(type(z))\r\nprint(z)\r\n<\/pre>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\n&lt;class 'tuple'&gt;\r\n(1, 2, 3, 4, 5, 6, 7, 8)\r\n<\/pre>\r\n\r\n<p>As we can see the unpacking operator has unpacked list x and list y into tuple that is z. We can also see that the result is a tuple.<\/p>\r\n\r\n\r\n<p>Let\u2019s write the same function using *Args.<\/p>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndef maxarea(*lis):\r\n \r\n    max = 0\r\n    for i in lis:\r\n        if i &gt; max:\r\n            max = i\r\n \r\n    return f&quot;rectangle which has the more area is {max}&quot;\r\n \r\n \r\nx = maxarea(100, 60, 50, 200)\r\ny = maxarea(100, 60, 50, 200, 9000)\r\nz = maxarea(100, 60, 50, 20, 90)\r\nprint(x)\r\nprint(y)\r\nprint(z)\r\n<\/pre>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\nrectangle which has the more area is 200\r\nrectangle which has the more area is 9000\r\nrectangle which has the more area is 100\r\n<\/pre>\r\n\r\n<p>In this code block we can see that now the arguments are dynamic, we can add any number of arguments that will be unpacked in the maxarea function to give us the desired result. Also, we can compare any number of areas in this context.<\/p>\r\n\r\n\r\n<h2 id=\"fifthparagraph\">**kwargs in Python<\/h2>\r\n<p>The kwargs is like args but it accepts positional arguments. It uses ** operator which has some attributes like unpacking multiple positional arguments of any length, can also unpack dictionaries, can also used for combining two dictionaries.<\/p>\r\n<h4>Merging dictionaries<\/h4>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\na = {&quot;h&quot;: 1, &quot;n&quot;: 2}\r\nb = {&quot;m&quot;: 5, &quot;l&quot;: 10}\r\n \r\nc = {**a, **b}\r\n \r\nprint(type(c))\r\nprint(c)\r\n \r\n\r\n\r\nWe can see from the above code that we have 2 dictionaries a and b which are merged using ** operator to give another dictionary.\r\nOutput:\r\n \r\n&lt;class 'dict'&gt;\r\n{'h': 1, 'n': 2, 'm': 5, 'l': 10}\r\n<\/pre>\r\n\r\n<p>When we use * operator instead of ** operator, the code for this case is illustrated below.<\/p>\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\na = {&quot;h&quot;: 1, &quot;n&quot;: 2}\r\nb = {&quot;m&quot;: 5, &quot;l&quot;: 10}\r\n \r\nc = {*a, *b}\r\n \r\nprint(type(c))\r\nprint(c)\r\n<\/pre>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\n&lt;class 'set'&gt;\r\n{'n', 'l', 'm', 'h'}\r\n<\/pre>\r\n\r\n<p>Hence, when the * operator is used on two dictionaries to merge, the out will be a set with only the keys from the dictionary.<\/p>\r\n\r\n\r\n<p>The maxarea function using **kwargs is illustrated in the below code block.<\/p>\r\n\r\n\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\ndef maxarea(**lis):\r\n \r\n    max = 0\r\n    for i in lis.values():\r\n        if i &gt; max:\r\n            max = i\r\n \r\n    return f&quot;rectangle which has the more area is {max}&quot;\r\n \r\n \r\nx = maxarea(a=1, b=2, c=3)\r\ny = maxarea(a=1, b=2)\r\nz = maxarea(a=1, b=2, c=3, d=9)\r\nprint(x)\r\nprint(y)\r\nprint(z)\r\n<\/pre>\r\n\r\n<pre class=\"brush: jscript; title: ; notranslate\" title=\"\">\r\nOutput:\r\nrectangle which has the more area is 3\r\nrectangle which has the more area is 2\r\nrectangle which has the more area is 9\r\n<\/pre>\r\n\r\n\r\n<p>In this blog about advanced functions in Python, we have covered topics like passing functions to other functions, using functions inside a function, *Args in Python, \u201c*\u201d operator in Python, **kwargs in Python, and more. The further topics which include classes will be covered in the <a href=\"https:\/\/firmbee.com\/python-classes\/\">next blog post.<\/a> Homework regarding advanced functions in Python is given below.<\/p>\r\n\r\n\r\n<img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/firmbee.com\/wp-content\/uploads\/Advanced_functions_in_Python-800x200.png\" alt=\"advanced_functions_in_Python\" width=\"800\" height=\"200\" class=\"alignnone size-medium wp-image-21208 img-fluid\" title=\"\" srcset=\"https:\/\/firmbee.com\/wp-content\/uploads\/Advanced_functions_in_Python-800x200.png 800w, https:\/\/firmbee.com\/wp-content\/uploads\/Advanced_functions_in_Python-900x225.png 900w, https:\/\/firmbee.com\/wp-content\/uploads\/Advanced_functions_in_Python.png 1200w\" sizes=\"auto, (max-width: 800px) 100vw, 800px\" \/>\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","protected":false},"excerpt":{"rendered":"This article will help the reader continue from the previous Python functions blog along with some basic applications in the real world. We will be [&hellip;]","protected":false},"author":26,"featured_media":21248,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"footnotes":""},"categories":[5,491,1],"tags":[],"class_list":["post-21205","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-blog","category-python-course","category-other"],"acf":{"faq":null,"seria_wpisow":"Python Course From Beginner to Advanced in 11 blog posts","tytul_w_serii":"Advanced functions in Python. Part 8 Python Course from Beginner to Advanced in 11 blog posts","":"","naglowek_spisu_tresci":"","spis-tresci-lista":null},"_links":{"self":[{"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/posts\/21205","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/users\/26"}],"replies":[{"embeddable":true,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/comments?post=21205"}],"version-history":[{"count":19,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/posts\/21205\/revisions"}],"predecessor-version":[{"id":32562,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/posts\/21205\/revisions\/32562"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/media\/21248"}],"wp:attachment":[{"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/media?parent=21205"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/categories?post=21205"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/firmbee.com\/wp-json\/wp\/v2\/tags?post=21205"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}