First of all, we need to understand what the function is and why we should use this?
Let’s understand this concept.
Where are trying to understand the function, it means we have been read about variables, statements, loops.
Let’s imagine we need to create a program where there are four programs like open account, credit account, debit account, print account statement.
As we have learned about statement and loop, these concepts can implement this concept but we need to execute one task at a time, other task does not affect with current execution task.
So we need a tool which contains statements or code related to the execution of task so that we use that at a time.
So the function is a block of statement or code which executes a code whenever it is called in a program, if the function is not called, function statements or code will not execute, and there will not be any kind of output.
So this kind of facility is provided by the function.
Normally in early programming languages like C, C++ there is a function that has 3 parts.
- Function declaration
- Function definition
- Function call
But Python programming has different strategies to create a function in python.
There is only a function definition and function call whenever a program is required to execute code.
Function in python
Syntax of function in python:
Function call in python
A basic example of a function in python.
A program to display a simple message “Hello, welcome to python” using a function.
def message(): #function definition print("Hello, welcome to python") message() #function call
Parameterized function in Python
When parameters are passed in function declaration or definition is called parameterized function.
def message(msg): # msg is a variable passed in function definition called parameter also print(msg) message("Hello, welcome to python") # This string is a string argument.
Variables pass to the function declaration, the definition is called parameters.
Variables pass to the function call are called arguments.
To calculate the sum of two numbers using a parameterized function.
def sum(x,y): z=x+y print(z) sum(10,20)
Non parameterized function in python
The Parameters are not passed to function declaration or definition is called non parameterized function.
def name(): print("My name is Aayat") name()
The return statement in python
The return statement, return execution of the program to where a function call.
def sum(x,y): return x+y z=sum(10,20) print("sum=",z)