Python - Python Function - Introduction Tutorial
The function is a block of reusable code that only runs when it is called.
There are many built-in function like print(), count(), etc.
But you can also create your own function, which is called a user-defined function.
Syntax for function creation-
def function_name(parameters):
statements
- Function block begin with a def keyword followed by function name and parenthesis(), and colon mark ':'.
- (Optional) Any parameter can be placed inside this parenthesis
- Statements will include the main logic of a code, It can also make use of parameters.
- (Optional) In the end, it can also return some value back to where it is called.
Calling a function-
To call a function use the function name followed by parenthesis.
Example-
# creating a function my_function
def my_function():
print("Hello World")
# calling a function my_function
my_function()
Output-
Hello World
Passing an argument
While calling a function, we can pass the multiple arguments if required.
It is specified inside the parenthesis while calling a function.
Example-
#Defing a function my_function() with parameter a
def my_function(a):
print("Hello "+a)
#Calling a function my_function() with argument "Sam"
my_function("Sam")
Output-
Hello Sam
In the above example, after calling a function my_function("Sam"), argument "Sam" passed to a definition my_function(a). It means a="Sam". then the print statement will run and "Hello Sam" will get printed.
Type Of Argument-
- Positional Argument
- Keyword Argument
- Default Argument
Positional Argument
In this number of arguments should match with a number of parameters and should be in the same order, otherwise, it will mismatch the output result.
Example-
# Function with both positional argument
def employee_data(emp_name , emp_age , emp_id):
print(emp_name)
print(emp_age)
print(emp_id)
# Passing positional argument
employee_data('fresherbell',25,123)
Output-
fresherbell
25
123
Keyword Argument
If you are not aware of how many arguments are passed and the exact ordering of an argument in the function definition. Then you can also pass the argument using the Key = Value pair.
Example-
#Defing a function my_function() with parameter c1,c2,c3(order not matter)
def my_function(c3,c1,c2):
print("Hello "+c3)
print("Hello "+c1)
#Calling a function my_function() with argumentc1="Sam",c2="Dam",c3="Man"
my_function(c1="Sam",c2="Dam",c3="Man")
Output-
Hello Man
Hello Sam
In the above example, after calling a function my_function(c1="Sam",c2="Dam",c3="Man"), argument Key and Value pair passed to a definition my_function(). Here, the order of parameters doesn't matter. then it can be printed using a key e.g print(c3])
Arbitrary argument - args*
If you are not aware of how many arguments are passed, then put * before the parameter name in the function definition.
This way the function will receive a tuple of arguments and can access the items using indexing.
Example-
#Defing a function my_function() with parameter *a
def my_function(*a):
for i in range(len(a)):
print(a[i])
print("Hello "+a[3])
print("Hello "+a[2])
#Calling a function my_function() with argument "Sam","Dam","Man","Wam"
my_function("Sam","Dam","Man","Wam")
Output-
Sam
Dam
Man
Wam
Hello Wam
Hello Man
In the above example, after calling a function my_function("Sam","Dam","Man","Wam"), argument "Sam","Dam","Man","Wam" passed to a definition my_function(a) in the form of tuple. It means a=("Sam","Dam","Man","Wam"). then it can be printed using indexing e.g print(a[1]) or using for loop.
Arbitrary Keyword Argument - **kwargs
If you are not aware of the exact ordering of an argument in the function definition. Then pass the argument using the Key = Value pair and put ** before the parameter name in the function definition.
This way the function will receive a dictionary of arguments and can access the items accordingly.
Example-
#Defing a function my_function() with parameter **val
def my_function(**val):
print("Hello "+val['c1'])
print("Hello "+val['c2'])
#Calling a function my_function() with argumentc1="Sam",c2="Dam",c3="Man"
my_function(c1="Sam",c2="Dam",c3="Man")
Output-
Hello Sam
Hello Dam
In the above example, after calling a function my_function(c1="Sam",c2="Dam",c3="Man"), argument Key and Value pair passed to a definition my_function() in the form of dictionary. It means val={c1="Sam",c2="Dam",c3="Man"} and can be printed using string indexing e.g print(val['c1'])
*args will work as a tuple, **kwargs will work as a dictionary
Example-
def employee_data(*args , **kwargs):
# args - tuple
# kwargs - dict
print(args)
print(kwargs)
if kwargs.get('employee_state'):
print(f"emp_state is present : {kwargs['employee_state']}")
employee_data('fresher' , 'bell' , 23, employee_state = 'Goa' , employee_location = 'india')
Output-
('fresher', 'bell', 23)
{'employee_state': 'Goa', 'employee_location': 'india'}
emp_state is present : Goa
Default Argument
If we call the function without an argument, and the default value is defined in the function definition. Then it will use the default value.
Example-
#Defing a function my_function() with default parameter
def my_function(a="Ram"):
print("Hello "+a)
#Calling a function my_function() with and without argument
my_function("Sam")
my_function()
Output-
Hello Sam
Hello Ram
In the above example, If we call a function my_function("Sam"), the function definition will use the argument that is passed. And if we call a function my_function() i.e without argument, the function definition will use the default parameter.
Positional argument with default argument
In this default argument should always be after a positional argument, otherwise, it will throw an error
Example-
# Function with both positional and default argument
def employee_data(emp_name , emp_age , emp_id, emp_location='india' , employee_state = 'Goa'):
print(emp_name)
print(emp_age)
print(emp_id)
print(emp_location)
print(employee_state)
# Passing positional argument
employee_data('fresherbell',25,123)
Output-
fresherbell
25
123
india
Goa
Scope of variable
A variable declared inside the function will not be visible outside the function. It is accessible only inside the function. Hence it is a local scope.
Variable declared outside the function can be accessible both inside and outside a function. Hence, it is a global scope.
Example-
#Declaring a variable inside the function
def my_function():
#local variable
a = 1
print(a)
print(b)
#global variable
a = 2
b = 3
#Calling a function my_function()
my_function()
print(a)
print(b)
Output-
1
3
2
3
Recursive Function
A recursive Function is a function that calls itself.
Find the factorial of a number using a recursive function
Example-
# Recursive Function - Factorial function calling itself till the condition become false
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
n = 5
print("The factorial of", n, "is", factorial(n))
Output-
The factorial of 5 is 120
Return statement in the function
- it is optional in function
- if not used returned statement default value will be none
- if used the returned statement then the value will be that statement
- if returned then the type of the function will be what is returned
- you can return any object
- you can return the function also
Example-
def evenorodd(a):
if a%2 == 0:
return 'even'
else:
return 'odd'
print(evenorodd(4))
Output-
even