top of page

Python Function

Function is a block code which can be reused many times by just calling it.

Define a function

def company():

    print("TechArena Learning Hub")

Defining a function won't give you the output. calling a function will give you the output.

Call a function

company()

Parameters

while defining a function, variables which we pass is called is an parameter.

Define a function

def add(x,y):

    print(x+y)

Arguments

While calling a function, value which we pass is called arguments.

Call a function

add(3,7)

one thing, we need to make sure that number of parameter should always equal to number of arguments else python will throw an error.

Variable length Arguments

By passing * in parameters, we can make our functions variable length function.

Create a function 

def add(*v):

    print(sum(v))

​

add(3,6,2,9,6)

Default Parameters

while defining a function, we can make a parameter default.

Define a function

def add(x,y = 10):

    print(x+y)

​

add(5,7)

add(3)

Print Vs Return

print will just print a value. function will not return any value and you cannot store it in another variable.

Print

def add(x,y):

    print(x+y)

​

a = add(3,5)

print(a)

Return

def add(x,y):

    return x+y

​

a = add(3,5)

print(a)

In the above example, we can see that value returned by an function is stored in a variable.

Lambda function

It is an anonymous function which means it doesn't have any name and everything is written on a single line.

Create a lambda function

x = lambda a,b : a+b

print(x(3,4))

on left side of the semicolon we will write the variables and on right side of it, we will write the expression which will return a value.

bottom of page