Python Functions are a group of
connected statements that are used to accomplish a computational, logical, or
evaluative activity in Python. The goal is to group together certain often
performed actions and create a function, so that instead of writing the same
code over and over for different inputs, we may call the function and reuse the
code contained within it.
Built-in and user-defined
functions are both possible. It contributes in maintaining the programme
simple, non-repetitive, and well-organized.
Types of Functions in Python
Built –in Function
Python provides a number of
functions that may be used directly. These are referred to as built-in
functions. Most of Python's built-in functions are included on this reference
page. Click Here
User Defined Function
User-defined functions are
functions that we define ourselves to do a certain purpose. We've already
spoken about how to define and call functions in Python.
Built-in functions are
functions that come pre-installed with Python. Library functions are when we
employ functions written by others in the form of a library.
User-defined functions include
all other functions that we create on our own. As a result, our user-defined
function might be considered a library function by others.
Syntax
def function_name(parameters):
"""docstring""" statement(s) return
expression
|
Creating a Function
The def keyword can be used to build a Python function.
Example:
# Write a Program to Creating a Function in Python
def run(): print("Welcome to www.a2pstudy.blogspot.com")
|
Calling a Function
After constructing a function,
we may call it by using the function's name followed by parentheses holding the
function's parameters.
Example:
# Write a Program to Creating/Calling a Function in
Python
def run(): print("Welcome to www.a2pstudy.blogspot.com
") # call a function run()
|
Output Welcome to www.a2pstudy.blogspot.com |
Function with Arguments
The values given inside the
function's parentheses are referred to as arguments. Any number of parameters
can be separated by a comma in a function.
Example:
# Write a Program to illustrate Function with Argument.
def evenOdd(x): if
(x % 2 == 0): print("even") else: print("odd")
# call the function evenOdd(2) evenOdd(3)
|
Output even odd |
Types of Arguments
Python supports various types
of arguments that can be passed at the time of the function call. Let’s discuss
each type in detail.
- Default arguments
- Keyword arguments
- Variable-length arguments
- *args (Non-Keyword Arguments)
- **kwargs (Keyword Arguments)
good
ReplyDeletesap pp online course fee