Functions
In its simplest form, it is a block of code that perform specific task(s).
Advantages of using Functions
- Code reusability: You are able to reuse the fucntion throughout your system without duplicating your code.
- Provides cleaner access to functionality.i.e I dont have to expose how I am performing a task other than calling the function.
- Modularization: Function helps you brak down what would have been one big complex system, into smaller ‘group/blocks’ that performs specific tasks that all work together.
- Another benefit of using functions is it easier to debug and test your functionalities.
- A collegue, reiewer or any concrned stake holder is able to read and understand your code if it is broken down to smaller functions .
Terms to know
Parameter: variable name that specifies the iput that a function expected
Arguments: Values passed to a function when it is called.
Types of parameters
- Positional : These are type of paremeters that must be passed in the same order as they appear in the function.
- Keyword parameters: parameters thatare specified by keywords rather than positions.
- Default parameters:These parameters have default values that are provided during functional defination.If other values are not provided the defualt values will be used.
- Variable-length : Type of parameters defination that allows a funtion to take a different number of parameters as need be. it is represented as `*args` for positional parameter and **kwargs for keyword parameter.
Lamda function
Anonymous function that is used to improve code reradability and reduce verbosity.They take any number parameters
Syntax of a function in python
def function_name():
pass #when you are not ready define th function yet.
def function_name(parameters):
some logic
return and/or print statements.
#lambda function
sum = x:x+x
print(sum(1,2,3))Functions are a building block in functional programming paradigm.They are first-class citizen and composable(can be combined with other functions to create a new function) and pure(always has the same output for the same input).
