Python - Functions

A Python function is a block of code in the program that performs specific task.
A Python function can optionally return the value.
A Python function can be reused whenever we need it in the program.
A Python function accepts the parameters and alter the function behaviour by changing the parameter.

Defining a Function

A python function starts with def keyword followed by name, parenthesis, and colon.

Example:

def calculate():
    print(“This is a calculate function”)
Calling a Function

You can call a python function whenever you need. In Python, you can call the function with function name.

Example:

def calculate():
    print(“This is a calculate function”)

calculate() 	## Calling a function
Defining a Function with parameters and arguments

Parameters can specify after function name and inside the parenthesis. You can specify multiple parameters in parenthesis by separating with comma.

An argument is an information or data passed to the python function.
The data can be passed from the function caller using the functions parameters.

In the below example, calculate() is a python function with one parameter i.e. num.

Example:

def calculate(num):
    print(Square of the number:” + num ** num)
calculate(4) 	# calling a function with argument 4.
calculate(10)	# calling a function with argument 10.
Defining a Function with default parameters

A python function can be used a default parameter value. In case, if you call the function without argument, it uses the default parameter value. This is very useful if you do not know the value to pass it.

Example:

def get_location(city = ”London”):
    print(“my work location is:”+city)

get_location("Bangalore")
get_location("")

In the above example, when you call the get_location function with the argument “Bangalore”, it uses that value and print city as “Bangalore”. When you call the get_location function without the argument value, it uses the default parameter value and print city as “London”.

Calling a Function with number of arguments

A Python function can be defined with multiple parameters and called with same number of arguments. When you defined the function with 3 parameters, you should call the function with 3 arguments only so that the arguments values passed to respective function parameters in parentheses.

Example:

In the below example, multiply() is a python function with 3 parameters i.e. num1, num2 & num3

def multiply(num1, num2, num3):
    print(“Multiplication result:”+ num1 * num2 * num3)

multiply(2, 5, 10)      # calling a function with arguments 2, 5 and 10.
multiply(25, 1.5, 2)    # calling a function with arguments 25, 1.5 and 2.
Defining a Function with *args (Arbitrary Arguments)

Python function can have as many arguments as possible. But, you have to make sure pass the same number of argument values while calling the function. Otherwise, it throws the error message.

Example:

def multiply(num1, num2):
    print(“multiplication result”+ num1 * num2)

multiply(2, 5, 7).

In the above example, you are passing 3 argument values (2, 5, & 7) instead of 2 arguments as you defined the multiply() function with 2 parameters. So, this program throws the error message since you have passed 3 argument values.

To deal with this issue, you can use *args as parameter in Python function.

Example:

def multiply(*args):
    total = 0
    for num in args:
        total *= num
    print(“Total value”+ total)

multiply(2,3,4)         ## calling a function with 3 arguments
multiply(2,3,4,5)       ## calling a function with 4 arguments
multiply(2,3,4,5,6)     ## calling a function with 5 arguments
Calling a Function with keyword arguments

Python function can be called with key, and value pair arguments.
The big advantage with keyword arguments is you don’t require to follow the order of the arguments.

Example:

def employee(emp1, emp2, emp3):
    print(“Employees are:”+emp1+” “+emp2+” “+emp3)

# calling a function without following order with key, value pair.
employee(emp2=”Tom”, emp3=”Josh”, emp1=”John”)
Defining a Function with **kwargs (Arbitray Keyword Arguments)

Python function can be defined with the parameter **kwargs. So, this python function can be called with as many keyword arguments as you want.

In the arbitrary arguments(*args), we need to follow the positional arguments, whereas in the keyword arguments(**kwargs), you do not need follow the order of arguments.

In this way, kwargs are considered as a dictionary and you can access the items accordingly.
Also, you can specify your own function name and add ** before to it.

The main advantage with keyword arguments(**kwargs) is you can just specify your own parameter name and add ** before the function if you do not know number of arguments need to pass while calling the function. Example: (**emp)

Example:

def employee(**emp):
    print(“employees are:”+ emp[emp1]+” “+emp[emp2]+” “+emp[emp3])

employee(emp2=”Tom”, emp3=”Josh”,emp1=”John”)
Variable Scope

Scope is the visibility/availability of the variable to use.
When you define the variable in function, that variable can be available inside that function only and it won’t be available to use outside of that function.
When you define the variable inside the program as global variable, it will be available to use anywhere in the program.

Example:

def get_name():
    name = “Tom”
    print(“Player name is: ”+ name) 	## Player name is: Tom

In the above example, the name variable visible inside get_score() function only.

Example:

def get_name():
    print(“Player name is:”+name) 		## Player name is: Tom
name=”Tom”

In the above example, the name variable visible in program level. It can be available to use anywhere in the program.

Example:

def get_name():
    name = “Tom”
print(“Player name is:”+ name)      # Throws NameError message

In the above example, name variable defined inside the get_name() function and it is visible only inside that function. So, the above program throws the error message since you are accessing from outside of the function.

Return Statement

In Python, the function is optionally return the value.
A return statement in the function, ends the execution part and return the value to the caller.

Example:

def add(a, b):
    return a + b	# Returns the sum of a and b
total = add(5,10)	# Calling add function with 2 arguments and receive the total as 15.
Return multiple values

A return statement can return multiple values as tuple, list, dictionary, and set.
You can specify the multiple values with comma.

Example:

def calculator(a, b):
    return a + b, a – b, a * b, a % b
result = calculator(20, 5)
print(“Add:”+result[0])
print(“Subtract:”+result[1])
print(“Multiplication:”+result[2])
print(“Division:”+result[3])
Return a Function

A return statement can return another function from a function.

Example:

# first method
def calculate(a,b):
    x = a + b
    y = a - b
    #second method
    return lambda: print ( x * y)
# generate a object of first method
returned_calculate_funcation = calucate(10,5)
# print object
print(returned_calculate_funcation)
# call second method by first method
returned_calculate_funcation()

Output

< Object reference >
75


Related Tutorials