Functions are generally defined for the piece of code which is repeatedly used across many places in a project. Functions are also defined to separate complex processing from the main code. Broadly there are two type of functions in Python:
Non-Parameterized Function def <function_name>(): some_code some_code [return something] #Optional Parameterized Function def <function_name>(parameter1[,parameter2]): some_code some_code [return something] #Optional
Example 1:
def multipleOf3():
for i in range(1,16):
if i%3==0:
print(i)
>>> multipleOf3()
Output:
3
6
9
12
15
Example 1:
def my_function(fname):
print( "Hello " + fname)
>>> my_function('Dbmstutorials')
Output: Hello Dbmstutorials
Example 2: Multiple parameters
def add_two_numbers(num1, num2):
print( num1 + num2)
>>> add_two_numbers(3,7)
Output: 10
Example 1:
def my_function(country = "India"):
print("I am from " + country)
>>> my_function()
Output: I am from India
>>> my_function('USA')
Output: I am from USA
Example 1:
def my_function_add_2(num):
return num+2
>>> my_function_add_2(3)
Output: 5
Example 2: Return multiple values as Tuple
def my_function_add_2(num):
return num+2, num
>>> my_function_add_2(3)
Output: (5, 3)
Example 1: Here instead of arg, any identifier can be defined
def my_function_unlimited_arguments(*arg):
cnt=1
for i in arg:
print("Parameter "+str(cnt)+": "+str(i))
cnt = cnt+1
>>> my_function_unlimited_arguments('a',5,'dbms',6)
Output:
Parameter 1: a
Parameter 2: 5
Parameter 3: dbms
Parameter 4: 6
Example 1:
def my_function_unlimited_kv_arguments(**kvargs):
for i in kvargs:
print("Key "+str(i)+", Value:"+str(kvargs[i]))
>>> my_function_unlimited_kv_arguments(a ='Apple', b ='One', Pie ='3.14')
Output:
Key a, Value:Apple
Key b, Value:One
Key Pie, Value:3.14
>>> my_function_unlimited_kv_arguments(a ='Apple', 1='One' , Pie ='3.14')
Output:
File "<stdin>", line 1
SyntaxError: keyword can't be an expression
Note: key passed as parameter must be valid identifier, for example only numbers can be passed as key and it will fail error(keyword can't be an expression).
Lambda Function
var_name = lambda <comma separated parameters> : [direct calculations which will be returned as output]
Example 1:
x = lambda a : a + 10
>>> print(x(5))
Output: 15
Example 2: With 2 parameters
x = lambda a, b : a * b
>>> print(x(5, 6))
Output: 30
Example 3:
def multiplier_with_lambda(num):
return lambda a : a * num
>>> doubleData = multiplier_with_lambda(2)
>>> print(doubleData(11))
Output: 22
>>> multiplier_with_lambda(11)(2)
Output: 22
>>> tripleData = multiplier_with_lambda(3)
>>> print(tripleData(11))
Output: 33
>>> multiplier_with_lambda(11)(3)
Output: 33