How to create a function in python
This tutorial is how to create a function in python. Python function is a block of code that performs some specific task. and Its function name has unique.
The python function’s main aim of the program more readable, and organized. and Reduce repeated code.
Define a function
Create in python function use def keyword. Define function name is unique for the function and in parenthesis, you can specify your parameters.
Function block starts with colon(:).
Syntax
def function_name(paramenter):
# statement
Example
def fun_call():
print("Python function is called!")
fun_call() function which not take any arguments. when fun_call function called It print text on the screen.
Call a function
Python function call to specify the function name and specify the parameters in parentensis().
Syntax
def function_name(parameter): # define function
# statement
function_name(parameter) # call function
Example
def fun_call(): print("Function called successfully!") fun_call() fun_call() Output: Function called successfully! Function called successfully!
Function with parameter
Python function call to specify the parameter in the function different-different parameters.
Syntax
def function_name(parameter):
# statement
function_name(parameter)
Example
def checkoddeven(number): if number%2 == 0: print("Even number") else: print("Odd number") checkoddeven(30) checkoddeven(7) checkoddeven(55) Output: Even number Odd number Odd number
Function with return
Python function Use return statement to return value from the function.
Syntax
def function_name(paramenter):
# statement
return value
Example
def checkMaxValue(list_data): max_val = list_data[0] for val in list_data: if val > max_val: max_val = val return max_val list_data = [1,32,33,55,98,99,56,46,22] print("Maximum value is :",checkMaxValue(list_data)) Output: Maximum value is : 99
Default value
The python function call to the Default parameter automatically gets even if don’t pass arguments while calling the function.
Syntax
def function_name(variable1=value,variable2=value,n):
# statement
Example
def studentInfo(firstname,lastname="Joi",age=33): print("first name : ",firstname,", last name : ",lastname,", age : ",age) studentInfo("Die") studentInfo("Hitesh",age=22) # Change age studentInfo("Emaly","Kill") # Change lastname Output: first name : Die , last name : Joi , age : 33 first name : Hitesh , last name : Joi , age : 22 first name : Emaly , last name : Kill , age : 33
Multiple parameters
The python function call to handling an unknown amount of items to function we use an asterisk (*)
sign-in function.
Syntax
def function_name(*argument):
# statement
Example
def display_fun(name,*friends): print("Name :",name) print("Friends :",lastname) display_fun("Emily kill","joi","die","john") Output: Name : Emily kill Friends : ('joi', 'die', 'john')
*friends variable is converts the friends argument into a tuple.