USER DEFINED FUNCTION


Not only built-in functions, python also provides us facility to create our own task, called as user-defined functions. The user defined function in python begins with keyword def followed by function_name and then list of formal arguments enclosed within braces as follows:

def function_name(list of comma seperated arguments):
   statement
   statement
   

A simple python functions to add two numbers:

#function definition
def sum():
  '''
  This functions add 10 and 20
  '''
  a = 10
  b = 20
  result = a+b
  print(result)


# function call
sum()

For the above function, in function definition, the first statement enclosed as a string provides documentation about the function (which is optional) and the rest are valid python statements. Inorder to activate the function, the defined function need to be called as in function call section.

We can pass information to the function during function call, using a concept called function argument. The example below explain the concept:

# now let us modify the sum(), to add any two number using function arguments
def sum(a,b):
  result = a+b
  print(result)

sum(10,20)

Now the given function can add any two given numbers. we can pass as many arguments we can as function arguments:

# now the same function can be modified to add three numbers:
def sum(a,b,c):
  result = a+b+c
  print(result)

sum(10,20,30)

we can use, return statement to return the result of calculations aout of the function as follows:

# use of return statement, to return value from the function definition
def sum(a,b,c):
  result = a+b+c
  return result

result = sum(10,20,30)
print(result)

Now, let us understand the concept of user-defined function using some examples:

Python code: to check whether the given number is prime or not:

def is_prime(num):
    if num <= 1:
        return False
    for i in range(2, num//2):
        if num % i == 0:
            return False
    return True

# Example usage:
number = int(input("Enter a number: "))
if is_prime(number):
    print(number, "is a prime number")
else:
    print(number, "is not a prime number")

python supports the concept of global variables, if you want to access global variable within the given function use keyword: global as follows:

#accessing global variable from python function
k = 100
def test():
  global k
  k = k+20

test()
print(k) # display 120

Python code: To print fibonacci sequence upto n-terms:

def fibonacii(n):
  result = []
  i,j=0,1
  while(n>0):
    result.append(i)
    i,j= j,i+j
    n -=1
  return result
  
print(fibonacii(10))

Output:

[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]