{"id":6780,"date":"2018-09-03T21:58:12","date_gmt":"2018-09-03T16:28:12","guid":{"rendered":"https:\/\/techbeamers.com\/?p=6780"},"modified":"2025-11-30T10:52:44","modified_gmt":"2025-11-30T15:52:44","slug":"python-function","status":"publish","type":"post","link":"https:\/\/techbeamers.com\/python-function\/","title":{"rendered":"Python Function: A Practical Guide for Beginners"},"content":{"rendered":"\n<p>This tutorial walks you through the concept of a Python function. You\u2019ll learn how to create your own functions and use them to write modular code in Python<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-simple-steps-to-create-functions-in-python\"><a id=\"what\"><\/a>Simple Steps to Create a Python Function<\/h2>\n\n\n\n<p>In programming, a function is a label or name assigned to a piece of code. You can call that code any number of times by using the name. It is quite easy to define a function in Python using the &#8220;def&#8221; keyword. Before we get into the details of creating functions, first understand a little more about them.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-what-is-a-function-in-programming\">What is a Function in Programming?<\/h3>\n\n\n\n<p>A function in Python is an independent and reusable block of code that you can call any number of times from any place in a program. It is an essential tool for programmers to <a href=\"https:\/\/techbeamers.com\/python-string-splitting\/\" target=\"_blank\" rel=\"noreferrer noopener\">split<\/a> a big project into smaller modules. Here are some key points to consider.<\/p>\n\n\n\n<p><strong>1.<\/strong> They are the core building blocks of any programming language that a programmer must learn to use. Python provides several built-in methods for direct use and also allows you to define your custom functions.<\/p>\n\n\n\n<p><strong>2.<\/strong> A function in Python is a logical unit of code containing a sequence of statements indented under a name given using the &#8220;def&#8221; keyword.<\/p>\n\n\n\n<p><strong>3.<\/strong> Functions allow you to create a logical division of a big project into smaller modules. They make your code more manageable and extensible.<\/p>\n\n\n\n<p><strong>4.<\/strong> While programming, a function prevents you from adding duplicate code and promotes reusability.<\/p>\n\n\n\n<p>Let&#8217;s now quickly see what else are we going to learn from this tutorial.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-how-to-create-a-function-syntax\">Create a Python Function &#8211; Syntax<\/h3>\n\n\n\n<p>The syntax of a Python function is as follows.<\/p>\n\n\n\n<p><strong>Single line function:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def single_line(): statement<\/pre>\n\n\n\n<p><strong>Python function with docstring:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn(arg1, arg2,...):\n    \"\"\"docstring\"\"\"\n    statement1\n    statement2<\/pre>\n\n\n\n<p><strong>Nested Python function:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn(arg1, arg2,...):\n    \"\"\"docstring\"\"\"\n    statement1\n    statement2\n    def fn_new(arg1, arg2,...):\n        statement1\n        statement2\n        ...\n    ...<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-why-is-the-def-statement-used-in-python\"><a id=\"def-statement\"><\/a>Why is the &#8216;def&#8217; Statement Used in a Python Function?<\/h4>\n\n\n\n<p>Please read the below notes to understand the purpose of the &#8220;def&#8221; keyword in Python.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The &#8220;def&#8221; keyword is a statement for defining a function in Python.<\/li>\n\n\n\n<li>You start a function with the <a href=\"https:\/\/techbeamers.com\/python-keywords-identifiers-variables\/\" target=\"_blank\" rel=\"noreferrer noopener\">def keyword<\/a> and specify a name followed by a colon (:) sign.<\/li>\n\n\n\n<li>The &#8220;def&#8221; call creates the function object and assigns it to the name given.<\/li>\n\n\n\n<li>You can further re-assign the same function object to other names.<\/li>\n\n\n\n<li>Give a unique name to your function and follow the same rules as naming the identifiers.<\/li>\n\n\n\n<li>Add a meaningful <a href=\"https:\/\/techbeamers.com\/python-comment-vs-multiline-comment\/\" target=\"_blank\" rel=\"noopener\">docstring<\/a> to explain what the function does. However, it is an optional step.<\/li>\n\n\n\n<li>Now, start the function body by adding valid Python statements each indented with four spaces.<\/li>\n\n\n\n<li>You can also add a statement to return a value at the end of a function. However, this step is optional.<\/li>\n\n\n\n<li>Just press enter and remove the indentation to end a function.<\/li>\n\n\n\n<li>Since def is a statement, you can use it anywhere a statement can appear \u2013 such as nested in an if clause or within another function.<\/li>\n<\/ul>\n\n\n\n<p><strong>Example :<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">if test:\n        def test(): # First definition\n            ...\n    else:\n        def test(): # Alternate definition\n            ...\n    ...<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-how-to-call-a-function-in-python\"><a id=\"function-call\"><\/a>How to Call a Function in Python?<\/h4>\n\n\n\n<p>By using the def keyword, you learned to create the blueprint of a function that has a name, parameters to pass, and a body with valid <a href=\"\/understand-python-statement-indentation\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python statements<\/a>.<\/p>\n\n\n\n<p>The next step is to execute it. You can do so by calling it from the Python script, inside a function, or directly from the Python shell.<\/p>\n\n\n\n<p>To call a function, you need to specify the function name with relevant parameters, and that&#8217;s it.<\/p>\n\n\n\n<p>Follow the below example to learn how to call a function in Python.<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><a href=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/09\/Python-function-for-modular-programming.png\"><img loading=\"lazy\" decoding=\"async\" width=\"341\" height=\"381\" src=\"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/09\/Python-function-for-modular-programming.png\" alt=\"Python function for modular programming\" class=\"wp-image-6781\"\/><\/a><\/figure>\n<\/div>\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-example-of-a-function-call\"><a id=\"call-example\"><\/a>Example of a Function Call<\/h4>\n\n\n\n<p>It&#8217;s a simple example where a function &#8220;typeOfNum()&#8221; has nested functions to decide if a number is either odd or even.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def typeOfNum(num): # Function header\n    # Function body\n    if num % 2 == 0:\n        def message():\n            print(\"You entered an even number.\")\n    else:\n        def message():\n            print(\"You entered an odd number.\")\n    message()\n# End of function\n\ntypeOfNum(2)  # call the function\ntypeOfNum(3)  # call the function again<\/pre>\n\n\n\n<h3 class=\"wp-block-heading has-medium-font-size\" id=\"h-polymorphism-in-python\"><a id=\"polymorphism\"><\/a>Polymorphism in Python<\/h3>\n\n\n\n<p>In Python, function polymorphism is possible as we don&#8217;t specify the argument types while creating functions.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The behavior of a function may vary depending on the arguments passed to it.<\/li>\n\n\n\n<li>The same function can accept arguments of different object types.<\/li>\n\n\n\n<li>If the objects find a matching interface, the function can process them.<\/li>\n<\/ul>\n\n\n\n<p><strong>Example :<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def product(x, y) : return x * y\nprint(product(4, 9)) # function returns 36\nprint(product('Python!', 2))  # function returns\n                              # Python!Python!\nprint(product('Python 2 or 3?', '3')) # TypeError occurs<\/pre>\n\n\n\n<p>The above example clarifies that we can pass any two objects to the product() function which supports the &#8216;*&#8217; operator.<\/p>\n\n\n\n<p>The concept above we&#8217;ve explained is known as polymorphism. Some points which you should remember are as follows.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Python is a dynamically typed language which means the types correlate with values, not with variables. Hence, the polymorphism runs unrestricted.<\/li>\n\n\n\n<li>That&#8217;s one of the primary differences between Python and other statically typed languages such as C++ or Java.<\/li>\n\n\n\n<li>In Python, you don&#8217;t have to mention the specific <a href=\"https:\/\/techbeamers.com\/python-data-types-learn-basic-advanced\/\" target=\"_blank\" rel=\"noopener\">data types<\/a> while coding.<\/li>\n\n\n\n<li>However, if you do, then the code limits to the types anticipated at the time of coding.<\/li>\n\n\n\n<li>Such code won&#8217;t allow other compatible types that may be required in the future.<\/li>\n\n\n\n<li>Python doesn&#8217;t support any form of function overloading.<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-parameters-in-a-function\"><a id=\"function-parameters\"><\/a>Parameters in a Function<\/h3>\n\n\n\n<p>We often use the terms <strong>parameters and arguments<\/strong> interchangeably. However, there is a <strong>slight difference between them<\/strong>.<\/p>\n\n\n\n<p><strong>Parameters<\/strong> are the variables used in the function definition whereas <strong>arguments<\/strong> are the values we pass to the function parameters.<\/p>\n\n\n\n<p>Python supports different variations of passing parameters to a function. Before we discuss each of them, you should read the following notes.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The argument gets assigned to the local variable name once passed to the function.<\/li>\n\n\n\n<li>Changing the value of an argument inside a function doesn&#8217;t affect the caller.<\/li>\n\n\n\n<li>If the argument holds a mutable object, then changing it in a function impacts the caller. Refer &#8211; <a href=\"https:\/\/techbeamers.com\/python-pass-by-reference-vs-pass-by-value\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python Pass by Reference or Value<\/a><\/li>\n\n\n\n<li>We call the passing of immutable arguments as Pass by Value because Python doesn&#8217;t allow them to change in place.<\/li>\n\n\n\n<li>The passing of mutable arguments happens to be Passed by Pointer in Python because they are likely to be affected by the changes inside a function.<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-example-immutable-vs-mutable\"><a id=\"immutable-vs-mutable\"><\/a>Example: Immutable vs. Mutable<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">def test1(a, b) :\n    a = 'Garbage' # 'a' receives an immutable object\n    b[0] = 'Python' # 'b' receives a list object\n                    # list is mutable\n                    # it can undergo an in place change\ndef test2(a, b) :\n    a = 'Garbage 2'\n    b = 'Python 3' # 'b' now is made to refer to new\n                   # object and therefore argument 'y'\n                   # is not changed\n\narg1 = 10\narg2 = [1, 2, 3, 4]\ntest1(arg1, arg2)\nprint(\"After executing test 1 =&gt;\", arg1, arg2)\ntest2(arg1, arg2)\nprint(\"After executing test 2 =&gt;\", arg1, arg2)<\/pre>\n\n\n\n<p>After execution, the above code prints the following.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">After executing test 1 =&gt; 10 ['Python', 2, 3, 4]\nAfter executing test 2 =&gt; 10 ['Python', 2, 3, 4]<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-example-avoid-change-in-mutable-argument\">Example: Mutable Arguments<\/h4>\n\n\n\n<pre class=\"wp-block-preformatted\">def test1(a, b) :\n    a = 'Garbage'\n    b[0] = 'Python'\n\narg1 = 10\narg2 = [1, 2, 3, 4]\n\nprint(\"Before test 1 =&gt;\", arg1, arg2)\ntest1(arg1, arg2[:]) # Create an explicit copy of mutable object\n                     # 'y' in the function.\n                     # Now 'b' in test1() refers to a\n                     # different object which was initially a\n                     # copy of 'arg2'\n                            \nprint(\"After test 1  =&gt;\", arg1, arg2)<\/pre>\n\n\n\n<p>After execution, the above code prints the following.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Before test 1 =&gt; 10 [1, 2, 3, 4]\nAfter test 1  =&gt; 10 [1, 2, 3, 4]<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-standard-arguments\"><a id=\"standard-arguments\"><\/a>Standard Arguments<\/h4>\n\n\n\n<p>The standard arguments are those that you pass as specified in a Python function definition. It means without changing their order and without skipping any of them.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn(value):\n    print(value)\n    return\n\nfn()<\/pre>\n\n\n\n<p>Executing the above code throws the below error as we&#8217;ve not passed the single argument required.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">TypeError: fn() missing 1 required positional argument: 'value'<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-keyword-based-arguments\"><a id=\"keyword-arguments\"><\/a>Keyword-based Arguments<\/h4>\n\n\n\n<p>When you assign a value to the parameter (such as param=value) and pass it to the function (like fn(param=value)), then it turns into a keyword argument.<\/p>\n\n\n\n<p>If you pass the keyword arguments to a function, then Python determines it through the parameter name used in the assignment.<\/p>\n\n\n\n<p>See the below example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn(value):\n    print(value)\n    return\n\nfn(value=123) # output =&gt; 123\nfn(value=\"Python!\") # output =&gt; Python!<\/pre>\n\n\n\n<p>While using keyword arguments, you should make sure that the name in the assignment should match the one in the function definition. Otherwise, Python throws the TypeError as shown below.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">fn(value1=\"Python!\") # wrong name used in the keyword argument<\/pre>\n\n\n\n<p>The above function call causes the following error.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">TypeError: fn() got an unexpected keyword argument 'value1'<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-arguments-with-default-values\"><a id=\"default-arguments\"><\/a>Arguments with Default Values<\/h4>\n\n\n\n<p>Python functions allow setting the default values for parameters in the function definition. We refer to them as the default arguments.<\/p>\n\n\n\n<p>The callee uses these default values when the caller doesn&#8217;t pass them in the function call.<\/p>\n\n\n\n<p>The below example will help you clearly understand the concept of default arguments.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def daysInYear(is_leap_year=False):\n    if not is_leap_year:\n        print(\"365 days\")\n    else:\n        print(\"366 days\")\n    return\n\ndaysInYear()\ndaysInYear(True)<\/pre>\n\n\n\n<p>Here, the parameter &#8220;is_leap_year&#8221; is working as a default argument. If you don&#8217;t pass any value, it assumes the False default.<\/p>\n\n\n\n<p>The output of the above code is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">365 days\n366 days<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-variable-arguments\"><a id=\"variable-arguments\"><\/a>Variable Arguments<\/h4>\n\n\n\n<p>You may encounter situations when you have to pass additional arguments to a Python function. We refer to them as variable-length arguments.<\/p>\n\n\n\n<p><a href=\"https:\/\/techbeamers.com\/python-print-with-examples\/\" target=\"_blank\" rel=\"noreferrer noopener\">Python&#8217;s print()<\/a> is itself an example of such a function that supports variable arguments.<\/p>\n\n\n\n<p>To define a function with variable arguments, you need to prefix the parameter with an asterisk (*) sign. Follow the below syntax.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn([std_args,] *var_args_tuple ):\n   \"\"\"docstring\"\"\"\n   function_body\n   return_statement<\/pre>\n\n\n\n<p>Check out the below example for better clarity.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def inventory(category, *items):\n    print(\"%s [items=%d]:\" % (category, len(items)), items)\n    for item in items:\n        print(\"-\", item)\n    return\n\ninventory('Electronics', 'tv', 'lcd', 'ac', 'refrigerator', 'heater')\ninventory('Books', 'python', 'java', 'c', 'c++')<\/pre>\n\n\n\n<p>The output of the above code goes like this.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">Electronics [items=5]: ('tv', 'lcd', 'ac', 'refrigerator', 'heater')\n- tv\n- lcd\n- ac\n- refrigerator\n- heater\nBooks [items=4]: ('python', 'java', 'c', 'c++')\n- python\n- java\n- c\n- c++<\/pre>\n\n\n\n<p>Please note that you can choose to have a formal argument or not in the function definition along with the variable arguments.<\/p>\n\n\n\n<p>You may choose to skip the variable arguments while calling the function. In such a case, the <a href=\"https:\/\/techbeamers.com\/python-tuple\/\" target=\"_blank\" rel=\"noopener\">tuple<\/a> would remain empty.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-use-variables-in-functions\">Use Variables in Functions<\/h3>\n\n\n\n<p>Two types of variables can exist in a Python function. Let&#8217;s check out.<\/p>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-local-variables-inside-a-function\"><a id=\"local-variables\"><\/a>Local Variables Inside a Function<\/h4>\n\n\n\n<p>A local variable has visibility only inside a code block such as the function def. They are available only while the function is executing. Check out the below example of using local variables.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn(a, b) :     \n    temp = 1\n    for iter in range(b) :\n        temp = temp*a\n    return temp\n\nprint(fn(2, 4))\n\nprint(temp) # error : can not access 'temp' out of scope of function 'fn'\nprint(iter) # error : can not access 'iter' out of scope of function 'fn'<\/pre>\n\n\n\n<p>In this example, we try to access local variables outside the function body which results in the NameError.<\/p>\n\n\n\n<p>The function\u2019s local variables don&#8217;t retain values between calls. The names used inside a def do not conflict with variables outside the def, even if you&#8217;ve used the same names elsewhere.<\/p>\n\n\n\n<p>In Python, the variables assignment can occur at three different places.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Inside a def \u2013 it is local to that function<\/li>\n\n\n\n<li>In an enclosing def \u2013 it is nonlocal to the nested functions<\/li>\n\n\n\n<li>Outside all def(s) \u2013 it is global to the entire file<\/li>\n<\/ul>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-global-variables-in-a-function\"><a id=\"global-variables\"><\/a>Global Variables in a Function<\/h4>\n\n\n\n<p>The global keyword is a statement in Python. It enables variables (names) to retain changes that live outside a def, at the top level of a module file.<\/p>\n\n\n\n<p>In a single global statement, you can specify one or more names separated by commas.<\/p>\n\n\n\n<p>All the listed names are attached to the enclosing module\u2019s scope when assigned or referenced within the function body.<\/p>\n\n\n\n<p>Check the below example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">x = 5\ny = 55\ndef fn() :\n    global x\n    x = [3, 7]\n    y = [1, 33, 55]\n    # a local 'y' is assigned and created here\n    # whereas, 'x' refers to the global name\nfn()\nprint(x, y)<\/pre>\n\n\n\n<p>In the above code, &#8216;x&#8217; is a global variable that will retain any change in its value made in the function. Another variable &#8216;y&#8217; has local scope and won&#8217;t carry forward the change.<\/p>\n\n\n\n<p>Let&#8217;s now see how a globally declared name behaves in two different Python functions.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">foo = 99\n\ndef fn1() :\n    foo = 'new' # new local foo created\n\ndef fn2() :\n    global foo\n    foo = 'update' # value of global foo changes<\/pre>\n\n\n\n<p>In the next example, let&#8217;s see how global behaves with the import statement.<\/p>\n\n\n\n<p>Here, we have the following three scripts:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>mod_global.py:<\/strong> It contains the global definition and a function changing and displaying values.<\/li>\n\n\n\n<li><strong>test1.py:<\/strong> It imports the first file and accesses the global variable.<\/li>\n\n\n\n<li><strong>test2.py:<\/strong> It uses the &#8220;from&#8221; clause to&nbsp;import the first file and access the global variable.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\"># mod_global.py\ndef fn1() :\n   global x\t\n   x = [1,2] ; y = [20, 200]\n   # a local 'y' is created \u2013 availableonly within 'f1'\n   # 'x' can be accessed anywhere after a call to 'f1'\nfn1()\ntry :\n    print(x, y) # name 'y' is not defined \u2013 error\nexcept Exception as ex:\n    print('y -&gt;', ex)\n    print('x -&gt;', x)<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># test1.py\nimport mod_global\nprint('test1 -&gt;', mod_global.x)<\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\"># test2.py\nfrom mod_global import *\nprint('test2 -&gt;', x)<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-general-function-rules\">General Function Rules<\/h3>\n\n\n\n<p>While creating and calling the functions, you should know about the following rules.<\/p>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-name-resolution-in-a-python-function\"><a id=\"name-resolution\"><\/a>Name Resolution in a Python Function<\/h4>\n\n\n\n<p>It is essential to understand how name resolution works in case of a def statement.<\/p>\n\n\n\n<p>Here are a few points you should keep in mind.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>The name assignments create or change local names.<\/li>\n\n\n\n<li>The <a href=\"https:\/\/techbeamers.com\/python-programming-mistakes\/\" target=\"_blank\" rel=\"noopener\">LEGB rule<\/a> comes in the picture for searching the name reference.\n<ul class=\"wp-block-list\">\n<li>local &#8211; L<\/li>\n\n\n\n<li>then enclosing functions (if any) &#8211; E<\/li>\n\n\n\n<li>next comes the global &#8211; G<\/li>\n\n\n\n<li>and the last one is the built-in &#8211; B<\/li>\n<\/ul>\n<\/li>\n<\/ul>\n\n\n\n<p>To gain more understanding, run through the below example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">#var = 5\ndef fn1() :\n   #var = [3, 5, 7, 9]\n   def fn2() :\n      #var = (21, 31, 41)\n      print(var)\n   fn2()\nfn1()\t# uncomment var assignments one-by-one and check the output\nprint(var)<\/pre>\n\n\n\n<p>After uncommenting the first &#8220;var&#8221; assignment, the output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">5\n5<\/pre>\n\n\n\n<p>Next, after uncommenting the second &#8220;var&#8221; assignment as well, the output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">[3, 5, 7, 9]\n5<\/pre>\n\n\n\n<p>Finally, if we uncomment the last &#8220;var&#8221; assignment, then the result is as follows.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">(21, 31, 41)\n5<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-variable-scope-in-functions\"><a id=\"scope\"><\/a>Variable Scope in Functions<\/h4>\n\n\n\n<p>Python functions can access names in all available enclosing def statements.<\/p>\n\n\n\n<p>Check the below example.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">X = 101 # global scope name - unused\ndef fn1():\n   X = 102 # Enclosing def local\n   def fn2():\n      print(X) # Reference made in nested def\n   fn2() # Prints 102: enclosing def local\nfn1()<\/pre>\n\n\n\n<p>The scope lookup remains in action even if the enclosing function has already returned.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn1():\n   print('In fn1')\n   X = 100\n   def fn2(): \n      print('In fn2')\n      print(X) # Remembers X in enclosing def scope\n   return fn2 # Return fn2 but don't call it\naction = fn1() # Make, return function\naction() # Call fn2() now: prints 100<\/pre>\n\n\n\n<p>The output is as follows.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">In fn1\nIn fn2\n100<\/pre>\n\n\n\n<h4 class=\"wp-block-heading has-medium-font-size\" id=\"h-return-values-from-a-python-function\"><a id=\"return-statement\"><\/a>Return Values from a Python Function<\/h4>\n\n\n\n<p>In Python functions, you can add the &#8220;return&#8221; statement to return a value.<\/p>\n\n\n\n<p>Usually, the functions return a single value. But if required, Python allows returning multiple values by using the collection types such as <a href=\"https:\/\/techbeamers.com\/python-programming-questions-list-tuple-dictionary\/\" target=\"_blank\" rel=\"noreferrer noopener\">using a tuple or list<\/a>.<\/p>\n\n\n\n<p>This feature works like the call-by-reference by returning tuples and assigning the results back to the original argument names in the caller.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def returnDemo(val1, val2) :\n   val1 = 'Windows'\n   val2 = 'OS X'\n   return val1, val2 # return multiple values in a tuple\n\nvar1 = 4\nvar2 = [2, 4, 6, 8]\n\nprint(\"before return =&gt;\", var1, var2)\nvar1, var2 = returnDemo(var1, var2)\nprint(\"after return  =&gt;\", var1, var2)<\/pre>\n\n\n\n<p>The above code gives the following output.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">before return =&gt; 4 [2, 4, 6, 8]\nafter return =&gt; Windows OS X<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-python-function-examples\"><a id=\"more-examples\"><\/a>Python Function Examples<\/h3>\n\n\n\n<p>We have compiled a few distinct Python function examples. Check these and try to practice with them.<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Check out a general function call example.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def getMin(*varArgs) :\n    min = varArgs[0]\n    for i in varArgs[1:] :\n        if i &lt; min :\n            min = i\n    return min\n\nmin = getMin(21, -11, 17, -23, 6, 5, -89, 4, 9)\nprint(min)<\/pre>\n\n\n\n<p>The output is as follows.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">-89<\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>Next is an example of the recursive function.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def calcFact(num) :\n    if(num != 1) :\n        return num * calcFact(num-1)\n    else :\n        return 1\n\nprint(calcFact(4))<\/pre>\n\n\n\n<p>The output is as follows.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">24<\/pre>\n\n\n\n<p>Also Read: <a href=\"https:\/\/techbeamers.com\/higher-order-functions-in-python\/\" target=\"_blank\" rel=\"noreferrer noopener\">Higher Order Functions in Python<\/a><\/p>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-python-functions-as-objects\"><a id=\"function-as-object\"><\/a>Python Functions as Objects<\/h3>\n\n\n\n<p>Yes, Python treats everything as an object and functions are no different.<\/p>\n\n\n\n<p class=\"has-medium-font-size\"><strong>You can assign a function object to any other name.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def testFunc(a, b) : print('testFunc called')\nfn = testFunc\nfn(22, 'bb')<\/pre>\n\n\n\n<p>The output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">testFunc called<\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>You can even pass the&nbsp;function object to other functions.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn1(a, b) : print('fn1 called')\ndef fn2(fun, x, y) : fun(x, y)\nfn2(fn1, 22, 'bb')<\/pre>\n\n\n\n<p>The output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">fn1 called<\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>You can also embed a function object in data structures.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def fn1(a) : print('fn1', a)\ndef fn2(a) : print('fn2', a)\n\nlistOfFuncs = [(fn1, \"First function\"), (fn2, \"Second function\")]\nfor (f, arg) in listOfFuncs : f(arg)<\/pre>\n\n\n\n<p>The output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">fn1 First function\nfn2 Second function<\/pre>\n\n\n\n<p class=\"has-medium-font-size\"><strong>You can return a function object from another function.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">def FuncLair(produce) :  \n    def fn1() : print('fn1 called')\n    def fn2() : print('fn2 called')\n    def fn3() : print('fn3 called')\n    if produce == 1 : return fn1\n    elif produce == 2 : return fn2\n    else : return fn3\n\nf = FuncLair(2) ; f()<\/pre>\n\n\n\n<p>The output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">fn2 called<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-function-attributes\"><a id=\"function-attribute\"><\/a>Function Attributes<\/h3>\n\n\n\n<p>Python functions also have attributes.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>You can list them via the dir() built-in function.<\/li>\n\n\n\n<li>The attributes can be system-defined.<\/li>\n\n\n\n<li>Some of them can be user-defined as well.<\/li>\n\n\n\n<li>The dir() function also lists the user-defined attributes.<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-preformatted\">def testFunc():\n    print(\"I'm just a test function.\")\n\ntestFunc.attr1 = \"Hello\"\ntestFunc.attr2 = 5\ntestFunc()\nprint(dir(testFunc))<\/pre>\n\n\n\n<p>The output is:<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">I'm just a test function.\n['__annotations__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__globals__', '__gt__', '__hash__', '__init__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'attr1', 'attr2']<\/pre>\n\n\n\n<p>You can utilize the function attributes to archive state information instead of using any of the globals or nonlocal names. Unlike the nonlocals, attributes are accessible anywhere the function itself is, even from outside its code.<\/p>\n\n\n\n<p>We&#8217;ve covered the essential concept of a Python function in this tutorial. You should now try to use these concepts&nbsp;in your routine programming tasks.<\/p>\n\n\n\n<p>Before you leave. share this post on social media (<a href=\"https:\/\/www.linkedin.com\/company\/techbeamers\/\" target=\"_blank\" rel=\"noreferrer noopener\">Linkedin<\/a>\/<a href=\"https:\/\/twitter.com\/TechBeamers\" target=\"_blank\" rel=\"noreferrer noopener\">Twitter<\/a>). It would help us run this site free for our users.<\/p>\n\n\n\n<p><strong>Enjoy coding,<br>TechBeamers.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>This tutorial walks you through the concept of a Python function. You\u2019ll learn how to create your own functions and use them to write modular code in Python Simple Steps to Create a Python Function In programming, a function is a label or name assigned to a piece of code. You can call that code [&hellip;]<\/p>\n","protected":false},"author":321,"featured_media":6782,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":"","jetpack_post_was_ever_published":false},"categories":[92],"tags":[],"class_list":{"0":"post-6780","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python-programming-tutorials"},"jetpack_featured_media_url":"https:\/\/techbeamers.com\/wp-content\/uploads\/2018\/09\/Python-Function-A-Complete-Overview.png","_links":{"self":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6780","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/users\/321"}],"replies":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/comments?post=6780"}],"version-history":[{"count":1,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6780\/revisions"}],"predecessor-version":[{"id":23565,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/posts\/6780\/revisions\/23565"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media\/6782"}],"wp:attachment":[{"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/media?parent=6780"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/categories?post=6780"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/techbeamers.com\/wp-json\/wp\/v2\/tags?post=6780"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}