Python Function:
A function is a block of code which only runs when it is called.
You can pass data which is known as parameters into a function.
After getting parameters function passes some result.
Creating a Function:
def keyword is used to create function.
Example:
def first_func():
print("Hello first function")
print("Hello first function")
Here we have created a function.
Calling a Function:
Example:
def first_func():
print("Hello first function")
my_function() #calling function
Output:
Hello first function
print("Hello first function")
my_function() #calling function
Output:
Hello first function
Parameters in function:
One can add as many parameters, just separate them with a comma.
Example:
def first_func(names):
print(names + "Hello")
first_func("Ara")
first_func("Toob")
Output:
Ara Hello
Toob Hello
Note:The following example has a function with one parameter (names).
print(names + "Hello")
first_func("Ara")
first_func("Toob")
Output:
Ara Hello
Toob Hello
Note:The following example has a function with one parameter (names).
Default Parameter Value:
Example:
def first_func(names = "Poot"):
print(names + "Hello")
first_func()
first_func("Toob")
Output:
Poot Hello
Toob Hello
Note:If we call the function without parameter, it uses the default value.
print(names + "Hello")
first_func()
first_func("Toob")
Output:
Poot Hello
Toob Hello
Note:If we call the function without parameter, it uses the default value.
Return Values:
Use the
return
statement,to let function to return a value.
Example:
def my_function(x):
return 5 + x
print(my_function(3))
print(my_function(5))
print(my_function(9))
return 5 + x
print(my_function(3))
print(my_function(5))
print(my_function(9))
Output:
8
10
14
Key Arguments:
Example:
def my_function(car3, car2, car1):
print("The car is " + car3)
my_function(car1 = "BMW", car2 = "MERCS", car3 = "TOYA")
print("The car is " + car3)
my_function(car1 = "BMW", car2 = "MERCS", car3 = "TOYA")
Output:
The car are TOYA
Arbitrary Arguments:
If you do not know how many arguments that will be passed into your function, add a
*
before the parameter name in the function definition.
Example:
def my_function(*cars):
print("The best car is " + cars[1])
my_function("BMW", "MERCS", "TOYA")
print("The best car is " + cars[1])
my_function("BMW", "MERCS", "TOYA")
Output:
The best car is MERCS
Recursive function:
Python also accepts function recursion, which means a defined function can call itself.
Example:
def calc_factorial(k):
if(k == 1):
return 1
else:
return(k * calc_factorial(k-1))
if(k == 1):
return 1
else:
return(k * calc_factorial(k-1))
num = 3
print("The factorial of num is ",calc_factorial(num))
print("The factorial of num is ",calc_factorial(num))
Output:
6
Passing a List as parameter:
Example:
def my_function(vehicle):
for x in vehicle:
print(x)
cars = ["BMW", "BCW", "BKW"]
my_function(cars)
for x in vehicle:
print(x)
cars = ["BMW", "BCW", "BKW"]
my_function(cars)
Output:
BMW
BCW
BKW
0 Comments