filmov
tv
Python functions declaring and passing parameters with return value and calling the function

Показать описание
User defined Functions are used to execute some task which is frequently used. Code reuse is the main reason for using functions. We can use def keyword to declare a function.
def my_fun():
Functions can take any input parameter in the form of integer, string or list or may not take any argument as input. Functions may or may not return any value to the parent calling script.
def my_fun():
print("Welcome")
my_fun() # Calling the function
Once a function is defined it has to be called to use. Without calling the function it will not be executed.
We can pass more than one parameter to function. Here is a simple code to add two input numbers and return the sum of the numbers.
def my_fun(n1,n2):
return n1+n2
print(my_fun(12,15)) # 27
We can return sum of numbers to calling string
We can pass list to function. All elements will be added and sum is returned to calling script.
def my_sum(my_list):
sum=0
for i in my_list:
sum=sum+i
return sum
my_list=[1,5,7,12]
print("Sum = ",my_sum(my_list))
We can pass string as parameters and return to calling function.
We can use default value against each parameter. Once we declare a default value then all parameters to the right of it has to be declared as default value.
We can list all built in function available in Python, total number of functions available in Python installation is 153.
def my_fun():
Functions can take any input parameter in the form of integer, string or list or may not take any argument as input. Functions may or may not return any value to the parent calling script.
def my_fun():
print("Welcome")
my_fun() # Calling the function
Once a function is defined it has to be called to use. Without calling the function it will not be executed.
We can pass more than one parameter to function. Here is a simple code to add two input numbers and return the sum of the numbers.
def my_fun(n1,n2):
return n1+n2
print(my_fun(12,15)) # 27
We can return sum of numbers to calling string
We can pass list to function. All elements will be added and sum is returned to calling script.
def my_sum(my_list):
sum=0
for i in my_list:
sum=sum+i
return sum
my_list=[1,5,7,12]
print("Sum = ",my_sum(my_list))
We can pass string as parameters and return to calling function.
We can use default value against each parameter. Once we declare a default value then all parameters to the right of it has to be declared as default value.
We can list all built in function available in Python, total number of functions available in Python installation is 153.