Python Functions

Posted on Aug. 3, 2019
python
1306

A Python Function is a sequence of statements which are executed when it is called. So we can call that function wherever we want without rewriting that statements again and again.

Python function has following things to follow

  • a name to function i.e identifier (Required)
  • arguments to function (Optional)
  • body i.e statements inside a function (Required)
  • return something (Optional)

Below are the two examples of python functions.

1. A function named count_of_char will take two arguments ( word, chr ), count the chr count in word and return the count

def count_of_char(word, chr):
    count = 0
    for ch in word:
        if ch == chr:
            count += 1
    return count

print(count_of_char("this is sentence", "e"))

 

2. A function named say_hello will print Hello KoderPlace! when it is called.

def say_hello():
    print("Hello KoderPlace!")


say_hello() # function call
say_hello() # function call

 

  • A function name can be anything , it should starts with A-Z or a-z or even with _ (underscore). Also reserved keywords may not be used as identifiers.
  • if we assigned an identified when calling a function, the value becomes what it(function) returns. By default function will return None if we don't return anything.

l_count = count_of_char("hello", "l") # l_count value will be 2

a = say_hello() # a value will be None

 

The main advantage of function is re usability of code, So no need to duplicate the same code. Whenever we need that functionality we can call that same function as many times we want.

There four different types of functions are in python.

  • User defined Functions
  • Recursive Functions
  • Lambda Functions also called Anonymous 
  • Built in Functions

Above two examples are User defined Functions. Basically these functions helps divide our program to different modular components. So we can manage and debug the code easily.

 

Recursive Functions

A function which will call itself is called recursive function. These Recursion concept can be implemented in many cases like tree traversal techniques like preorder, postorder. 

Recursive functions also take same time and memory to execute as iterators but some times it will make code simpler and easy to understand.

We have to take care of infinite recursive loop. Below is a simple example of recursive function.

def factorial(n):
    if n == 1:
        return n
    return n * factorial(n-1)


print(factorial(8))

 

You can find about remaining function below.

Lambda Functions in Python. lambda functions can be used with map, filter and reduce in python

 




0 comments

Please log in to leave a comment.