18 posts
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
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
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.
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
Please log in to leave a comment.
18 posts