What are functions?
A function is a block of statements that can be used repeatedly in our code. Saves our time.
Types of functions
There are some built-in functions that are part of Python.
Alternatively, we can define tasks according to our needs.
For simple understanding, we can stitch our own clothes for our convenience python allows you to create such types of functions and they are named User-defined functions
def function_name(argument_1, argument_2, ...) : statement1 statement2
here we created a function with
- def keyword
- unique function name
- passing arguments
- condition statements for our needs
now the question is
How to call functions in python
function_name(arg_1, arg_2) Argument operations:
we can call a function by using the function name, with parameters passed inside the parenthesis.
Simple example for python function
def avg_num(p, q): print("Average of ",p," and ",q, " is ",(p+q)/2) avg_num(5, 6)
Average of 5 and 6 is 5.5
- Line 1
- created a function using def keyword
- named the function as “avg_num”
- passed parameters p and q
- Line 2
- to display the parameters and the calculated output we’re using print builtin function
- providing our condition for average as (p+q)/2
- Line 3
- calling the function using the functions created unique name and passing the values to the parameters
We can also call a function without arguments
def function_name() : statement1 statement2