5 Things to Know About Python functions | by Aditya Kousik Cotra | Towards Data Science

Functions are an effective way to reuse program codes. Using functions have the benefit of saving space and our choice of name makes our program easily readable. Functions can be defined without an input and are not necessarily required to produce an output.
There are many built-in functions in python but we can create our own functions.
In python, a function is defined using the defkeyword.
>>> def myfunc():      print("Python functions are easy to learn.")>>> myfunc() #calling function'Python functions are easy to learn.'
Functions mainly help you to structure your program. It is better to decompose long programs into functions, each one having its own purpose, making its structure transparent like this:
data = extract_data(source)results = analyze(data)present(results)
Appropriate use of functions makes the program more readable and maintainable. Moreover, it is easier to make changes to a function without being concerned about the rest of the program.
In this article, we will discuss five topics, which I think are important to know about functions. These topics will help you understand functions better.
Function definitions create new local scope for variables. When a new variable is assigned inside the function body, it is defined only inside the function. The variable is not visible outside the function. So we can choose any name when defining variables without being concerned about variables outside the function.
For example
>>> x = 10>>> def myfunc():        x = 5
In the above function, the variable x assigned to 10 outside the function and assigned to 5 inside the function. Now, when we print x outside the function:
>>> x10
The variable x does not change outside the function since the scope of x defined inside the function is limited to the function itself.
Arguments, also called parameters, are used to pass information into a function. There are two types of arguments:
Keyword arguments: An argument preceded by an identifier (key1 = value1 ) in a function call or passed as a value in dictionary preceded by ** .
ratio(numerator=10, denominator=4)ratio(**{'numerator':10,'denominator':4})
Positional arguments: An argument which is not a keyword argument. The value is passed into a function directly whose position represents a variable in the function. It can also be passed as elements of an iterable preceded by * .
ratio(10,4)ratio(*(10,4))
Interestingly, we can also pass function as an argument. For example, we can pass the built-in function len() or a user-defined function vowel_present() as arguments to another function:
>>> sent = ['Python', 'functions', 'are', 'amazing']>>> def execute_func(prop):        return [prop(word) for word in sent]>>> execute_func(len)[6, 9, 3, 7]>>> def vowel_present(word):...     for x in word:            if x in 'aeiou':                return True        return False>>> execute_func(vowel_present)[True, True, True, True]
Python functions do not require us to specify the type of input arguments. So it’s necessary to check the input variable type before executing the function.
def is_vowel(char): #Returns True if char is vowel, False otherwise.    if char in 'aeiou':        return True    else:        return False>>> is_vowel(5)False
For example, in the function above, the data type of number is not specified, but we expect the variable to be of type str of length one. However, if we pass an integer variable the function executes and returns False.
To avoid execution and raise an error, we can use the assert function like this.
def is_vowel(char):    assert(isinstance(char, str)) #raises error if not satisfied    assert(len(char)==1) #raises error if string not of length 1    if char in 'aeiou':        return True    else:        return False
If the assert statement fails, it produces an error and the function halts execution.
It is good practice to document our functions which describe it’s purpose, and provide it using the docstring at the top of the function definition like this:
def is_vowel(char):    '''Takes a string input of length one and returns True if vowel, False otherwise'''    assert(isinstance(char, str))    assert(len(char)==1)     if char in 'aeiou':        return True    else:        return False
Docstrings of any function can be found by running the help function. It can also be retrieved using the attribute __doc__ .
>>> help(is_vowel)Help on function is_vowel in module __main__:is_vowel(char)    Takes a string input of length one and returns True if vowel, False otherwise>>> is_vowel.__doc__'Takes a string input of length one and returns True if vowel, False otherwise'
Try running help(sklearn) to get the docstring of the sklearn library.
In this article, we mainly dealt with applications of functions and how they help build well-structured programs. In the next article, we will deal with python modules and how they help program efficiently.