{"id":20848,"date":"2022-12-12T06:31:00","date_gmt":"2022-12-12T05:31:00","guid":{"rendered":"https:\/\/expert-only.com\/?p=20848"},"modified":"2023-01-06T10:45:37","modified_gmt":"2023-01-06T09:45:37","slug":"user-defined-functions-in-python","status":"publish","type":"post","link":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/","title":{"rendered":"User-defined functions in Python"},"content":{"rendered":"\n<h4 class=\"has-text-align-center wp-block-heading\"><strong><em>Tutorial to learn how to create user-defined functions in Python using arguments, scope and recursivity.<\/em><\/strong><\/h4>\n\n\n\n<p>Functions, including user-defined  functions in Python, are blocks of organized, reusable code that are given a name and used to perform a specific task. They provide modularity and code reuse in programming. They are used to perform a specific task, and they can be called upon whenever that task is needed. Functions are a fundamental building block of Python and are an essential part of writing clean, efficient, and reusable code.<\/p>\n\n\n\n<p>This tutorial is following the two previous ones, about the <a href=\"https:\/\/expert-only.com\/en\/python\/introduction-to-python-programming\/\">introduction to Python programming<\/a>, followed by the <a href=\"https:\/\/expert-only.com\/en\/python\/python-data-types\/\">Python data types<\/a>, and the last one about how to <a href=\"https:\/\/expert-only.com\/en\/python\/basic-python-syntax\/\">use the Python basic syntax<\/a> to write code.<\/p>\n\n\n\n<p>In this course, you will learn about different types of functions in Python, including built-in functions and user-defined functions. But also anonymous functions, also called lambda functions, and recursive ones. You will also learn about function arguments, including required arguments, keyword arguments, default arguments, and variable-length arguments.<\/p>\n\n\n\n<p>You will also learn about the scope of variables, including global variables and local variables. Finally, you will learn about modules and packages, which are used to organize and reuse code in Python.<\/p>\n\n\n\n<div id=\"ez-toc-container\" class=\"ez-toc-v2_0_82_2 ez-toc-wrap-center counter-hierarchy ez-toc-counter ez-toc-grey ez-toc-container-direction\">\n<div class=\"ez-toc-title-container\">\n<p class=\"ez-toc-title\" style=\"cursor:inherit\">Table of Contents<\/p>\n<span class=\"ez-toc-title-toggle\"><\/span><\/div>\n<nav><ul class='ez-toc-list ez-toc-list-level-1 ' ><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-1\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#1-introduction-to-user-defined-python-functions\" >1. Introduction to user-defined Python functions<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-2\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#2-define-a-function-in-python\" >2. Define a function in Python<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-3\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#3-user-defined-python-functions-arguments\" >3. User-defined Python functions arguments<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-4\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#31-required-arguments\" >3.1 Required arguments<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-5\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#32-keyword-arguments\" >3.2 Keyword arguments<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-6\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#33-default-arguments\" >3.3 Default arguments<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-7\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#34-variable-length-arguments\" >3.4 Variable-length arguments<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-8\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#4-scope-of-variables-in-python\" >4. Scope of variables in Python<\/a><ul class='ez-toc-list-level-3' ><li class='ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-9\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#41-local-variables\" >4.1 Local Variables<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-3'><a class=\"ez-toc-link ez-toc-heading-10\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#42-global-variables\" >4.2 Global Variables<\/a><\/li><\/ul><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-11\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#5-anonymous-functions-lambda-functions\" >5. Anonymous Functions (Lambda Functions)<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-12\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#6-recursion\" >6. Recursion<\/a><\/li><li class='ez-toc-page-1 ez-toc-heading-level-2'><a class=\"ez-toc-link ez-toc-heading-13\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#7-conclusion-on-user-defined-python-functions-benefits\" >7. Conclusion on user-defined Python functions benefits<\/a><\/li><\/ul><\/nav><\/div>\n<h2 class=\"wp-block-heading\" id=\"h-1-introduction-to-user-defined-python-functions\"><span class=\"ez-toc-section\" id=\"1-introduction-to-user-defined-python-functions\"><\/span>1. Introduction to user-defined Python functions<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>User-defined functions are inspired by <a href=\"https:\/\/dlmf.nist.gov\/front\/introduction\" target=\"_blank\" rel=\"noreferrer noopener\">mathematical functions<\/a>, where it is the definition of steps that gives a specific result from an argument.<\/p>\n\n\n\n<p>A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code reusing. As you already know, Python gives you many built-in functions like print(), etc. but you can also create your own functions. These functions are called user-defined functions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"2-define-a-function-in-python\"><\/span>2. Define a function in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can create user-defined Python functions to provide a required, specific functionality not provided by the built-in functions. Here are simple rules to define a function in Python programming.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Function blocks begin with the keyword def followed by the function name and parentheses ( ( ) ).<\/li>\n\n\n\n<li>Any input parameters or arguments should be placed within these parentheses. You can also define parameters inside these parentheses.<\/li>\n\n\n\n<li>The first statement of a function can be an optional statement &#8211; the documentation string of the function or docstring.<\/li>\n\n\n\n<li>The code block within every function starts with a colon (:) and is indented.<\/li>\n\n\n\n<li>The statement return [expression] exits a function, optionally passing back an expression to the caller. A return statement with no arguments is the same as return None.<\/li>\n<\/ul>\n\n\n\n<p>Here is an example of a user-defined function that takes two numbers as arguments and returns their sum.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def sum(a, b):\n   # This function returns the sum of two numbers\n\n   result = a + b\n   return result\n<\/pre>\n\n\n\n<p>Calling a Function Defining a function only gives it a name, specifies the parameters that are to be included in the function&#8217;s definition, and structures the blocks of code.<\/p>\n\n\n\n<p>To execute a function, you must call it from somewhere else in your code. You call a function by using the function name followed by parentheses. Consider this first example.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">result = sum(1, 2)\nprint(result)\n\n# output is : 3\n<\/pre>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"XN59Glhsz2\"><a href=\"https:\/\/expert-only.com\/en\/python\/basic-python-syntax\/\">Basic Python syntax with code examples<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;Basic Python syntax with code examples&#8221; &#8212; SQL and IT Tutorials\" src=\"https:\/\/expert-only.com\/en\/python\/basic-python-syntax\/embed\/#?secret=j5cPhp1BOS#?secret=XN59Glhsz2\" data-secret=\"XN59Glhsz2\" width=\"500\" height=\"282\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-3-user-defined-python-functions-arguments\"><span class=\"ez-toc-section\" id=\"3-user-defined-python-functions-arguments\"><\/span>3. User-defined Python functions arguments<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>You can call a user-defined function by using the following 4 types of formal arguments:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Required arguments<\/li>\n\n\n\n<li>Keyword arguments<\/li>\n\n\n\n<li>Default arguments<\/li>\n\n\n\n<li>Variable-length arguments<\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-1-required-arguments\"><span class=\"ez-toc-section\" id=\"31-required-arguments\"><\/span>3.1 Required arguments<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Required arguments are the arguments passed to a function in correct positional order. Here, the number of arguments in the function call should match exactly with the function definition.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def greet(name):\n   # This function greets to the person passed in as parameter\n   # by printing Hello followed by the person's name\n   print(\"Hello, \" + name + \". Good morning!\")\n\ngreet('Paul')\n\n# The output is \nHello, Paul. Good morning!\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-2-keyword-arguments\"><span class=\"ez-toc-section\" id=\"32-keyword-arguments\"><\/span>3.2 Keyword arguments<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>Keyword arguments are related to the function calls. When you use keyword arguments in a function call, the caller identifies the arguments by the parameter name.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def greet(name, greeting):\n   \"\"\"This function greets to the person with the provided greeting\"\"\"\n   print(greeting + \", \" + name)\n\ngreet(greeting = \"Hello\", name = \"Paul\")\n\n# output will be : \nHello, Paul\n\ufeff<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"33-default-arguments\"><\/span>3.3 Default arguments<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>A default argument is an argument that assumes a default value if a value is not provided in the function call for that argument. The following example gives an idea on default arguments, it prints default age if it is not passed.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def welcome(name, age = 28):\n   # This function write welcome to the person with the provided name.\n   # and prints its age\n   print(\"Welcome, \" + name + \". You are \" + str(age) + \" years old.\")\n\nwelcome(\"Ahmed\")\n\n# output of the code :\nHello, Ahmed. You are 28 years old.\n<\/pre>\n\n\n\n<p>You can also specify the value of an argument in the function call. In this case, the default value is overridden.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">welcome(\"Ahmed\", 32)\n\n# In this case, the output will be:\nWelcome, Ahmed. You are 32 years old.\n <\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-3-4-variable-length-arguments\"><span class=\"ez-toc-section\" id=\"34-variable-length-arguments\"><\/span>3.4 Variable-length arguments<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>You may need to process a function for more arguments than you specified while defining the function. These arguments are called variable-length arguments and are not named in the function definition, unlike required and default arguments.<\/p>\n\n\n\n<p>An asterisk (*) is placed before the variable name that holds the values of all non-keyword variable arguments. This tuple remains empty if no additional arguments are specified during the function call.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def greet(*names):\n   # This function greets all the persons in the names tuple\n   # names is a tuple with arguments\n   for name in names:\n      print(\"Welcome, \" + name)\n\ngreet(\"Ahmed\", \"Lee\", \"Monica\", \"Luke\", \"Steve\", \"John\")\n\n# the output of the line of code above is\nWelcome, Ahmed\nWelcome, Lee\nWelcome, Monica\nWelcome, Luke\nWelcome, Steve\nWelcome, John\n\ufeff<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-4-scope-of-variables-in-python\"><span class=\"ez-toc-section\" id=\"4-scope-of-variables-in-python\"><\/span>4. Scope of variables in Python<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>All variables in a program may not be accessible at all locations in that program. This depends on where you have declared a variable. The scope of a variable determines the portion of the program where you can access a particular identifier.<\/p>\n\n\n\n<p>There are two basic scopes of variables in Python:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong><em>Local variables<\/em><\/strong><\/li>\n\n\n\n<li><strong><em>Global variables<\/em><\/strong><\/li>\n<\/ul>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-4-1-local-variables\"><span class=\"ez-toc-section\" id=\"41-local-variables\"><\/span>4.1 Local Variables<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>A local variable is a variable that is defined inside a function. It can only be accessed from within the function in which it is defined. Here is an example of how to create and use a local variable in Python:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def foo():\n    x = \"local\"\n    print(\"x inside :\", x)\n\nfoo()\nprint(\"x outside:\", x)\n\n# Output\n\nx inside : local\nTraceback (most recent call last):\n  File \"&lt;stdin>\", line 7, in &lt;module>\nNameError: name 'x' is not defined\n<\/pre>\n\n\n\n<h3 class=\"wp-block-heading\" id=\"h-4-2-global-variables\"><span class=\"ez-toc-section\" id=\"42-global-variables\"><\/span>4.2 Global Variables<span class=\"ez-toc-section-end\"><\/span><\/h3>\n\n\n\n<p>A global variable is a variable that is defined outside of a function. It can be accessed from anywhere in the code, both inside and outside of functions. Check this other practical code example to create and use a Python global variable.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">x = \"global\"\n\ndef foo():\n    print(\"x inside :\", x)\n\nfoo()\nprint(\"x outside:\", x)\n\n# Output\nx inside : global\nx outside: global\n<\/pre>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"08RxZJ9zSs\"><a href=\"https:\/\/expert-only.com\/en\/python\/python-data-types\/\">Python data types with code examples<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;Python data types with code examples&#8221; &#8212; SQL and IT Tutorials\" src=\"https:\/\/expert-only.com\/en\/python\/python-data-types\/embed\/#?secret=stmfj98YMA#?secret=08RxZJ9zSs\" data-secret=\"08RxZJ9zSs\" width=\"500\" height=\"282\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-5-anonymous-functions-lambda-functions\"><span class=\"ez-toc-section\" id=\"5-anonymous-functions-lambda-functions\"><\/span>5. Anonymous Functions (Lambda Functions)<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Sometimes, you need to write a small function for a short period of time. In these cases, you can use an anonymous function, also known as a lambda function. Lambda functions are small functions without a name. They are defined using the lambda keyword, which has the following syntax:<\/p>\n\n\n\n<p>Here is an example of a lambda function in Python:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">double = lambda x: x * 2\nprint(double(5))\n\n# Output is 10\n<\/pre>\n\n\n\n<p>In this example, the lambda function <code>double<\/code> takes in one argument <code>x<\/code> and returns <code>x * 2<\/code>. When we call the function with the argument <code>5<\/code>, it returns <code>10<\/code>. Here is another example of a lambda function that takes in two arguments and returns the sum.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">sum = lambda x, y: x + y\n\nprint(sum(3, 4))\n\n# the output is 7 <\/pre>\n\n\n\n<p>It is also possible to use lambda functions as arguments of other Python functions, built-in or user-defined. For example, the following uses the <code>sort<\/code> function to sort a list of tuples based on the second element of each tuple.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">my_list = [(1, 2), (3, 1), (5, 4)]\n\nmy_list.sort(key = lambda x: x[1])\n\nprint(my_list)\n<\/pre>\n\n\n\n<p>This sorts the list in ascending order based on the second element of each tuple.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\"># result of the previous code\n[(3, 1), (1, 2), (5, 4)]\n<\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" id=\"h-6-recursion\"><span class=\"ez-toc-section\" id=\"6-recursion\"><\/span>6. Recursion<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>Recursion, also called recursivity, is a technique in which a function calls itself. It is used to solve problems that can be divided into smaller problems of the same kind. For example, the factorial of a number is the product of all the integers starting from 1 to that number. I.e., the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.<\/p>\n\n\n\n<p>Here is an example of a recursive function to calculate the factorial of a given number, here it is 5.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"python\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">def factorial(n):\n   print (\"iteration number : \" + str(n) )\n   if n == 1:\n      return 1\n   else:\n      return n * factorial(n-1)\n\nprint(factorial(5))\n\n<\/pre>\n\n\n\n<p><\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter size-full\"><img loading=\"lazy\" decoding=\"async\" width=\"660\" height=\"540\" src=\"https:\/\/expert-only.com\/wp-content\/uploads\/2023\/01\/python-functions-recursion-to-calculate-factorial.jpg\" alt=\"User-defined functions in Python with a recursive example to calculate a factorial value\" class=\"wp-image-20911\" srcset=\"https:\/\/expert-only.com\/wp-content\/uploads\/2023\/01\/python-functions-recursion-to-calculate-factorial.jpg 660w, https:\/\/expert-only.com\/wp-content\/uploads\/2023\/01\/python-functions-recursion-to-calculate-factorial-300x245.jpg 300w\" sizes=\"auto, (max-width: 660px) 100vw, 660px\" \/><figcaption class=\"wp-element-caption\">User-defined functions in Python with a recursive example to calculate a factorial value<\/figcaption><\/figure><\/div>\n\n\n<h2 class=\"wp-block-heading\"><span class=\"ez-toc-section\" id=\"7-conclusion-on-user-defined-python-functions-benefits\"><\/span>7. Conclusion on user-defined Python functions benefits<span class=\"ez-toc-section-end\"><\/span><\/h2>\n\n\n\n<p>First, user-defined Python functions provide modularity to the code. You can define functions to perform specific tasks and then call those functions from other parts of your code, which makes your code easier to read and maintain. Functions also promote code reuse. You can define a function once and use it multiple times in your code, which saves you time and effort.<\/p>\n\n\n\n<p>Functions in Python, or in any programming language in general, can help you write cleaner and more efficient code. By organizing the code into functions, it is easier to read, debug, and test. They also can improve the readability and understandability of the code, useful and even mandatory for a team of developers.<\/p>\n\n\n\n<p>By giving descriptive names to your functions and organizing your code into logical blocks, you can make it easier for others to understand your code. Overall, using functions in Python can help you write better, more efficient, and more organized code.<\/p>\n\n\n\n<p>To go further and learn about SSIS this time, here a step by step tutorial on <a href=\"https:\/\/expert-only.com\/en\/ssis\/import-xml-file-into-a-table-with-ssis\/\">how to import XML files into a SQL table using Integration Services<\/a>.<\/p>\n\n\n\n<figure class=\"wp-block-embed is-type-wp-embed is-provider-sql-and-it-tutorials wp-block-embed-sql-and-it-tutorials\"><div class=\"wp-block-embed__wrapper\">\n<blockquote class=\"wp-embedded-content\" data-secret=\"sdIEKz0Xv8\"><a href=\"https:\/\/expert-only.com\/en\/ssis\/import-xml-file-into-a-table-with-ssis\/\">Import an XML file into a SQL table with SSIS<\/a><\/blockquote><iframe loading=\"lazy\" class=\"wp-embedded-content\" sandbox=\"allow-scripts\" security=\"restricted\" style=\"position: absolute; clip: rect(1px, 1px, 1px, 1px);\" title=\"&#8220;Import an XML file into a SQL table with SSIS&#8221; &#8212; SQL and IT Tutorials\" src=\"https:\/\/expert-only.com\/en\/ssis\/import-xml-file-into-a-table-with-ssis\/embed\/#?secret=yB9qtlhGpW#?secret=sdIEKz0Xv8\" data-secret=\"sdIEKz0Xv8\" width=\"500\" height=\"282\" frameborder=\"0\" marginwidth=\"0\" marginheight=\"0\" scrolling=\"no\"><\/iframe>\n<\/div><\/figure>\n","protected":false},"excerpt":{"rendered":"<div class=\"mh-excerpt\"><p>Tutorial to learn how to create user-defined functions in Python using arguments, scope and recursivity. Functions, including user-defined functions in Python, are blocks of organized, reusable code that are given a name and used to perform a specific task. <a class=\"mh-excerpt-more\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\" title=\"User-defined functions in Python\">&#8230;<\/a><\/p>\n<\/div>","protected":false},"author":1,"featured_media":10364,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[657],"tags":[],"class_list":{"0":"post-20848","1":"post","2":"type-post","3":"status-publish","4":"format-standard","5":"has-post-thumbnail","7":"category-python"},"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v21.7 (Yoast SEO v26.2) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>User-defined functions in Python - Programming - Python tutorials<\/title>\n<meta name=\"description\" content=\"Tutorial on user-defined functions in Python with code examples to organize and reuse the same code to perform specific tasks efficiently.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"User-defined functions in Python\" \/>\n<meta property=\"og:description\" content=\"Tutorial on user-defined functions in Python with code examples to organize and reuse the same code to perform specific tasks efficiently.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\" \/>\n<meta property=\"og:site_name\" content=\"SQL and IT Tutorials\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/ExpertOnlyCom\/\" \/>\n<meta property=\"article:published_time\" content=\"2022-12-12T05:31:00+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2023-01-06T09:45:37+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1920\" \/>\n\t<meta property=\"og:image:height\" content=\"1080\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Expert-Only\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@expert_only\" \/>\n<meta name=\"twitter:site\" content=\"@expert_only\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Expert-Only\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\"},\"author\":{\"name\":\"Expert-Only\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef\"},\"headline\":\"User-defined functions in Python\",\"datePublished\":\"2022-12-12T05:31:00+00:00\",\"dateModified\":\"2023-01-06T09:45:37+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\"},\"wordCount\":1313,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/expert-only.com\/en\/#organization\"},\"image\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg\",\"articleSection\":[\"Python tutorials\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\",\"url\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\",\"name\":\"User-defined functions in Python - Programming - Python tutorials\",\"isPartOf\":{\"@id\":\"https:\/\/expert-only.com\/en\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg\",\"datePublished\":\"2022-12-12T05:31:00+00:00\",\"dateModified\":\"2023-01-06T09:45:37+00:00\",\"description\":\"Tutorial on user-defined functions in Python with code examples to organize and reuse the same code to perform specific tasks efficiently.\",\"breadcrumb\":{\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage\",\"url\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg\",\"contentUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg\",\"width\":1920,\"height\":1080},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"en\",\"item\":\"https:\/\/expert-only.com\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"User-defined functions in Python\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/expert-only.com\/en\/#website\",\"url\":\"https:\/\/expert-only.com\/en\/\",\"name\":\"SQL and IT Tutorials\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/expert-only.com\/en\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/expert-only.com\/en\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/expert-only.com\/en\/#organization\",\"name\":\"Expert-Only\",\"url\":\"https:\/\/expert-only.com\/en\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg\",\"contentUrl\":\"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg\",\"width\":381,\"height\":174,\"caption\":\"Expert-Only\"},\"image\":{\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/www.facebook.com\/ExpertOnlyCom\/\",\"https:\/\/x.com\/expert_only\",\"https:\/\/www.youtube.com\/channel\/UCMS5sR_FwAetB0FmciNvUaA\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef\",\"name\":\"Expert-Only\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/expert-only.com\/en\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g\",\"caption\":\"Expert-Only\"}}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"User-defined functions in Python - Programming - Python tutorials","description":"Tutorial on user-defined functions in Python with code examples to organize and reuse the same code to perform specific tasks efficiently.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/","og_locale":"en_US","og_type":"article","og_title":"User-defined functions in Python","og_description":"Tutorial on user-defined functions in Python with code examples to organize and reuse the same code to perform specific tasks efficiently.","og_url":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/","og_site_name":"SQL and IT Tutorials","article_publisher":"https:\/\/www.facebook.com\/ExpertOnlyCom\/","article_published_time":"2022-12-12T05:31:00+00:00","article_modified_time":"2023-01-06T09:45:37+00:00","og_image":[{"width":1920,"height":1080,"url":"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg","type":"image\/jpeg"}],"author":"Expert-Only","twitter_card":"summary_large_image","twitter_creator":"@expert_only","twitter_site":"@expert_only","twitter_misc":{"Written by":"Expert-Only","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#article","isPartOf":{"@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/"},"author":{"name":"Expert-Only","@id":"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef"},"headline":"User-defined functions in Python","datePublished":"2022-12-12T05:31:00+00:00","dateModified":"2023-01-06T09:45:37+00:00","mainEntityOfPage":{"@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/"},"wordCount":1313,"commentCount":0,"publisher":{"@id":"https:\/\/expert-only.com\/en\/#organization"},"image":{"@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg","articleSection":["Python tutorials"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/","url":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/","name":"User-defined functions in Python - Programming - Python tutorials","isPartOf":{"@id":"https:\/\/expert-only.com\/en\/#website"},"primaryImageOfPage":{"@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage"},"image":{"@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage"},"thumbnailUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg","datePublished":"2022-12-12T05:31:00+00:00","dateModified":"2023-01-06T09:45:37+00:00","description":"Tutorial on user-defined functions in Python with code examples to organize and reuse the same code to perform specific tasks efficiently.","breadcrumb":{"@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#primaryimage","url":"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg","contentUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2022\/09\/bulb-FF27E99B3EA_1920x1080.jpg","width":1920,"height":1080},{"@type":"BreadcrumbList","@id":"https:\/\/expert-only.com\/en\/python\/user-defined-functions-in-python\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"en","item":"https:\/\/expert-only.com\/en\/"},{"@type":"ListItem","position":2,"name":"User-defined functions in Python"}]},{"@type":"WebSite","@id":"https:\/\/expert-only.com\/en\/#website","url":"https:\/\/expert-only.com\/en\/","name":"SQL and IT Tutorials","description":"","publisher":{"@id":"https:\/\/expert-only.com\/en\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/expert-only.com\/en\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/expert-only.com\/en\/#organization","name":"Expert-Only","url":"https:\/\/expert-only.com\/en\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/","url":"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg","contentUrl":"https:\/\/expert-only.com\/wp-content\/uploads\/2017\/09\/cropped-logo_Expert-Only.jpg","width":381,"height":174,"caption":"Expert-Only"},"image":{"@id":"https:\/\/expert-only.com\/en\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/www.facebook.com\/ExpertOnlyCom\/","https:\/\/x.com\/expert_only","https:\/\/www.youtube.com\/channel\/UCMS5sR_FwAetB0FmciNvUaA"]},{"@type":"Person","@id":"https:\/\/expert-only.com\/en\/#\/schema\/person\/406a9576b52944f018739a42046873ef","name":"Expert-Only","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/expert-only.com\/en\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/084b15660763ff5b13bb60b2f52f97bb?s=96&d=identicon&r=g","caption":"Expert-Only"}}]}},"_links":{"self":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/20848","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/comments?post=20848"}],"version-history":[{"count":0,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/posts\/20848\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media\/10364"}],"wp:attachment":[{"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/media?parent=20848"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/categories?post=20848"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/expert-only.com\/en\/wp-json\/wp\/v2\/tags?post=20848"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}