Python Tutorials: User Defined functions In Python

Python Tutorials: In this part of Learning Python we Cover how to use, Python User-defined Functions
Written by Paayi Tech |17-Oct-2020 | 0 Comments | 560 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 the 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 have become a lot easy.
  • Time-saving and reduce the lines of code.
  • Reusability of code increases.

 

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

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

 

Function With the print statement:

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

def func1():

    print("Function is executed")

 

func1()

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

 

Function with a return statement:

Unlike the above example, the function with return value does not print the statement on function calls. For printing the statement, we first have to call the 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 a function with an 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 two arguments, and then we define another function that takes one argument and prints that argument. We gave the function add in the second function, and it prints the value of add function.

def add(num1,num2):

    return num1+num2

 

def printResult(func):

    print(func)

 

printResult(add(44,55))

 

Recursive Function:

A recursive function is calling a function within a function. The function repeats itself until the condition is fully satisfied. Recursive function breaks the function into many parts and then return the desired output.

Otherwise, we have to use lots of for loops and if-else statements for such tasks. We look into an example of recursive by reversing the string with the help of recursive function. In this function, we will use string slicing along with the 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 slices the first letter and concatenates at the end till the length of the string is equal to zero. When there is no more letter in a string, the function returns the reversed string in the program—another famous example of a recursive function factorial number. The factorial number can be calculated by using a recursive function.

 

The tree in the 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 the one digit, and then it multiplies 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 a default value, and this function is called function with a default value. Following is the example of a 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 additional functionality within a function. It adds a 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 the user is authenticated or not is not a good approach in each template, so decorators are used instead, which check automatically when the function is called. Similarly, in GUI designing of pyQT, it gives the decorator which implements multi-threading on each function, so the 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 2020, 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.