Python Functions
A function is a piece of code that performs some task when invoked. They are declared using the def keyword and then the function name, the parentheses (), and a colon.
Example:
def
my_func():
print("Hello Coders")
Types of functions
There are two types of functions:
- built-in functions
- user-defined functions
built-in functions
These operations are pre-defined in Python. A few examples of built-in operations are:
len(), sum(), type(), range(), dict(), list(), tuple(), set(),
print(),
etc.
user-defined functions
These are user-defined functions that are used to execute particular operations.
Example:
def
my_func(parameters):
# block of code
Call a function
To call a function, insert the function name with parentheses.
Example:
def
my_func():
print("Hello Coders")
my_func()
Output
Hello Coders
Function Arguments
Arguments are the parameters input into the function.
Example:
def
my_func(fname, lname):
print("Hello", fname, lname)
my_func("John", "Doe")
Output
Hello John Doe