User defined functions ( UDF)

Defining a function
def my_fun():
my_fun()  # Calling the function
We must call the function to use it. In above code there is no return value and there is no parameter passed as input to the function.

Passing parameter to function

We will pass one integer to the function and display the sum by adding 10 to it.
def my_fun(n): # function starts here 
# function ends here   

Python functions declaring and passing parameters with return value and calling the function

Note that we have maintained left indentation within the function.
We will pass more than one parameter to the function
def my_fun(n1,n2):
  return n1+n2
print(my_fun(12,15)) # 27
Using string
def my_welcome(abc):
  print("Welcome ", abc)
my_welcome("Alex") # Welcome Alex

Returning data from function

def my_sum(a, b):
   return sum1

print("Sum = ",my_sum(5,8))
Sum = 13

Passing list to function

We will pass a list to function and return the sum of all the elements
def my_sum(my_list):
   for i in my_list:
   return sum1

print("Sum = ",my_sum(my_list))
Output is here
Sum = 25

Returning a list from a function

def my_details(my_marks):
    return a
print("Details = {}".format(marks_final))
Output is here
Details = [20, 5.0, 4]

Passing string parameter to function

def my_string(str1,str2):
    str3=str1 + str2
    return str3
str_final=my_string('Welcome to',' Python')
print("Here is your final string : ",str_final)
Output is here
Here is your final string :  Welcome to Python

Default Arguments of function

We will not use any parameter so python will use its default value.
def my_details(my_language='Python'):
    print("Welcome to {}".format(my_language))
my_details()       # No parameter is passed 
my_details('PHP')  # One string is passed 
Output is here
Welcome to Python
Welcome to PHP
In above code we have called the function without any parameter in first line. In second line we have called the function with a parameter.

If any argument does not have a default value then we must supply that while calling the function. We can have any number of arguments with default value, but once we have default value then all arguments to the right of it must have default value.

This code will generate error. non-default argument follows default argument
def my_details(my_language='Python',my_database):
    print("Welcome to {} with {}".format(my_language,my_database))

We can change this code
def my_details(my_database,my_language='Python'):
    print("Welcome to {} with {}".format(my_language,my_database))

Output is here
Welcome to MySQL with PHP

Function returning more than 1 parameters

Python functions can return multiple values.
def my_fun(n1,n2):
  return n1+n2,n1-n2

print("Sum = ", result1)
print("Subtraction  = ", result2)
Sum =  27
Subtraction  =  -3
Using string
def my_welcome(abc1,abc2):
  print("Welcome ", abc1 ,'to ', abc2)
my_welcome("Alex", "Python")
Welcome  Alex to  Python

*args **args

This function will generate error.
def my_fun(i1,i2): # can take two arguments
    return i1+i2
print(my_fun(2,3,4)) # error 
TypeError: my_fun() takes 2 positional arguments but 3 were given
We can pass any number of arguments to the function by using *
def my_fun(*args): # can receive any number of arguments
    for i in args:
    return sum1
print(my_fun(2,3,4)) # 9 , passing 3 arguments 
print(my_fun(2,2,3,4)) # 11, passing 4 arguments 

** to pass key and value pairs

We can pass both key and its value to the function by using **.
def my_fun(**kwargs): # key value pair as input 
    print(kwargs['c']) # plus2net  
    for key, value in kwargs.items():
        print ("%s : %s" %(key, value))
my_fun(a=' Welcome',b=' to',c=' plus2net')
a :  Welcome
b :  to
c :  plus2net
We can use a single fixed parameter followed by any number of key-value pairs.
def greet_person(name, **attributes):
    greeting = f"Hello, {name}!"
    for attr, value in attributes.items():
        greeting += f" Your {attr} is {value}."
    return greeting

print(greet_person("Alex", age=30, city="New Delhi", hobby="painting"))
Hello, Alex! Your age is 30. Your city is New Delhi. Your hobby is painting.


We can include details about the function for user understanding by writing some text about the function. This we can do by using three single quotes or by using three double quotes.
About Docstrings used in class , module, function and methods
def my_add(x,y):
    '''Takes two inputs and returns the sum'''
    return x+y
print(my_add(5,7)) #12 
Here the output of the second print command.
Takes two inputs and returns the sum
We can read the docstrings of Python built in functions

Using function from different file

Here is our function my_add() kept inside the file
def my_add(x,y):
    return("Sum :", x+y)
Our main file uses this function. ( both files are kept in same directory )
from all_fun import  my_add
Output is here
('Sum :', 9)

Recursive function

Python recursive functions to call same function within the function code to get factorial of input

Function which calls itself during its execution.
To prevent recursive function to execute infinitely we need to keep conditional statement to come out of recursive.

Factorial of a number is multiplication of all number less than the input number.
n! = n*(n-1)*(n-2)*(n-3) …. .* 1
Factorial using recursive function
Let us understand this by using one example.
Factorial of a number
def fact(n):    
    print("The number is : ",n)
    if n==1:
        return 1
        result = n*fact(n-1)
        print("Part factorial = ", result)
        return result
print(" Final factorial :",fact(5))
Output is here
The number is :  5
The number is :  4
The number is :  3
The number is :  2
The number is :  1
Part factorial =  2
Part factorial =  6
Part factorial =  24
Part factorial =  120
 Final factorial : 120
There is a limit to using recursive functions calls. We can read the System setting and change this value to a new value by using getrecursionlimit() and setrecursionlimit() methods.
import sys
print(sys.getrecursionlimit()) # output 1000
sys.setrecursionlimit(2000)  # new limit to 2000
print(sys.getrecursionlimit()) # output 2000
More on Recursion

Sample codes using recursive functions

Sum of digits of an input number
Greatest Common Divisor & Lowest Common Multiple (LCM) of two input numbers

There are some functions which are defined as part of the core Python. These functions are always available for use. We call them built in functions in Python.

Questions on Functions Global, local and non-local variables Builtin Functions
Subscribe to our YouTube Channel here


* indicates required
Subscribe to plus2net

    Post your comments , suggestion , error , requirements etc here

    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 All rights reserved worldwide Privacy Policy Disclaimer