Functions in Python
0 3023
In Python, functions you can say that it is a group of statements or block that perform a certain task i.e. you give input to it and depending upon some code, it performs internally a particular task and then provides output. The function can run only when it is called.
Why we need functions in python
It makes the code more modular, reusable, organized, manageable and more readable.
Type of Function
Python contains a wide range of functions that do not need to create it. The user can just use the inbuilt function as per requirement and whereas user-defined functions that user can create their own function.
Creating a Function
The function can be created with the help of the def keyword.
Syntax
def fun_name(parameters):
statement(s)
where def is the keyword
fun-name be the name of the function that we want to create
parameters can be any value or information that user wants to pass in the function, one can add any many parameters it wants only there is a need to separate them by commas
Example
def createfunction():
print("confirmation from function")
createfunction()
Example of passing parameters in function
def my_function(fname):
print(fname + " welcome in codingtag")
my_function("python student")
my_function("c students")
my_function("Linus students")
Output
python student welcome in codingtag
c students welcome in codingtag
Linus students welcome in codingtag
Return statement
This statement is used to let the function to return values.
Example
def add(h):
return 355683 + h
print(add(3))
print(add(5))
print(add(9))
Output
355686
355688
355692
A simple program of adding two numbers with the use of function
def sum(z,y):
print("z=",z)
print("y=",y)
total = z+y;
return total
n = sum(15,68)
print("total of z and y is",n)
Output
z= 15
y= 68
total of z and y is 83
Global and local variable
Example
total=0#global variable
def sum(z,y):
print("z=",z)
print("y=",y)
total = z+y;#local variable
return total
n = sum(15,68)
print("total of z and y is",n)
print("total=",total)
Output
z= 15
y= 68
total of z and y is 83
total= 0
Documentation Strings
It is a method to document the function in python language. A multi-line string started and ended with triple quotes.
Example
def add(h):
""" it returns addition """
return 355683 + h
print(add(3))
print(add(5))
print(add(9))
Output
355686
355688
355692
Share:
Comments
Waiting for your comments