User Defined functions In Python

In this part of Learning Python we Cover how to use, Python User-defined Functions
Written by Paayi Tech |10-Apr-2019 | 0 Comments | 116 Views

It is not a good approach to write a code that is already written in a program. The repetition of the same code creates a mess and it is very time consuming. So not to write the same code again and again, the good approach is to define a function and use that function where it is needed. Python also gives the same functionality to define a function to optimize the code as well as time.

For defining a function there is a special keyword in python and that is def. Unlike C, C++, and Java there is no return type in python functions. The interpreter determines on run time what is the return type of that function. The code within the function body is same as we have studied in normal sequential programming.

Some advantages of Functional programming is as follows:

  • Easy to understand the code
  • Program testing and debugging become a lot easy.
  • Time saving and reduce the lines of code
  • Reusability of code increases.

 

Functions are further categorized into number of types. The types of functions are following:

  • Function without arguments
  • Function with arguments
  • Default argument function
  • Function with print statements
  • Function with return statements
  • Recursive function

 

Function With print statement:

This type of function print something when it is called. Following is the example of such function.

 

def func1():
    print("Function is executed")
 
func1()

 

In the above code the first two lines are function body and third line is for calling the function.

 

Function with return statement:

Unlike the above example function with return value does not print the statement on function calling. For printing the statement, we first have to call function in a variable and then printing that variable will give the return statement.

def func1():
    return("Return Function is executed")
 
value = func1()
print(value)

 

This type of function is used when we must get the value in a variable for further computation.

 

Function With Argument:

We can pass arguments within a bracket to make the functions more dynamic. The following example is function with argument which add two number and return the value.

 

def add(num1,num2):
    return num1+num2
 
 
res = add(44,55)
print(res)

 

We can also give the function as an argument in another function. In the following example we first create the function to add two numbers which take 2 arguments and then we define another function which take one argument and print that argument, we gave the function add in second function and it print the value of add function.

 

def add(num1,num2):
    return num1+num2
 
def printResult(func):
    print(func)
 
printResult(add(44,55))

 

 

Recursive Function:

Recursive function is calling function within a function. The function repeat itself until condition is fully satisfied. Recursive function breaks the function into many part and then return the desired output. Otherwise we have to use lots of for loops and if else statement for such tasks. We look into example of recursive by reversing the string with the help of recursive function. In this function we will use string slicing along with recursive function to make it happen.

 

def reverse(string):
    if len(string)<1:
        return string
    else:
        return reverse(string[1:])+string[0]
 
print(reverse('python programming is cool'))

 

#output

looc si gnimmargorp nohtyp

 

The above function slice the first letter and concatenate at the end till the length of the string is equal to zero, when there are no more letter in a string the function returns the reversed string in the program.

Another famous example of recursive function factorial number. Factorial number can be calculated by using recursive function.

The tree in recursive function will be as follow:

5

 

 

 

 

5

4

 

 

 

5

4

3

 

 

5

4

3

2

 

5

4

3

2

1

 

 

The function will subtract the value until it reaches to the 1 digit and then it multiply all the digits.

The code of the following problem is as follows:

def factorial(num):
    if num>1:
        return factorial(num-1)*num
    else:
        return 1
print(factorial(5))

 

Function With Default Value:

The parameterized function can be having default value and this function is called function with default value. Following is the example of default value function:

Def printName(name='Hassan'):
    print(name)
 
printName('Fiza')
printName('Faraz')
printName()

 

#Output

Fiza

Faraz

Hassan

 

 

Function Decorators:

Function decorator is a type of design pattern. It allows the functionality to add the addition functionality within a function. It adds special attribute to the function so we don't have to do it by hard coding again and again.

from functools import wraps
 
def decorator(func):
    @wraps(func)
    def decorateFunc():
        print("Before Executing function")
        func()
        print("After execution")
    return decorateFunc
 
@decorator
def pokemon():
    print("Pikachu I choose you")
 
 
pokemon()

 

#Output

Before Executing function

Pikachu I choose you

After execution

 

 

Decorators are used extensively for authorization. In web frameworks it is necessary to check if a person is authorized or not. To write a code to check if user is authenticated or not is not a good approach in each template so decorators are used instead which check automatically when function is call. Similarly, in GUI designing of pyQT it gives the decorator which implement multi-threading on each function so app does not crashes.

Builtin function:

  • abs(): abs() take a integer and returns the absolute value [abs(-5) = 5]
  • float(): Float takes a number and converted into float number [float(5) = 5.0]
  • sum(): sum() take the list or tuple of number and returns it sum

[sum([1,2,3]) = 6]

  • min(): min() take a list or tuple and returns minimum value in it.
  • max(): max() take a list or tuple and returns maximum value in it.
  • sorted(): sorted take a list and tuple and return the sorted list.
  • pow():  pow takes two integer, first one the number and second it power

[pow(2,3)=8]

  • hex(): hex() takes a number and returns the hexa decimal value of that number

[hex(255) = '0xff']

  • hash(): hash takes a string and return a hashed integer value, This is used for security purpose [hash('python')= -492500173043352990]
  • ord(): ord() takes a character and returns its ascii code [ord('A')=65]



Login/Sign Up

Comments




Related Posts



© Copyright 2019, All Rights Reserved. paayi.com

This site uses cookies. By continuing to use this site or clicking "I Agree", you agree to the use of cookies. Read our cookies policy and privacy statement for more information.