0% found this document useful (0 votes)
5 views22 pages

6. Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views22 pages

6. Functions

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

Python Functions

Python Function
A function in Python is a way to group a set of related
statements together to perform a particular operation. It
helps break down complex problems into smaller,
manageable pieces of code.

Python has a DRY principle like other programming


languages. DRY stands for Don’t Repeat Yourself.
Consider a scenario where we need to do some
action/task many times. We can define that action
only once using a function and call that function
whenever required to do the same activity.
Why do we need functions?
Divides the code (or more accurately: the
problem) into well-isolated pieces, and encodes
each of them in the form of a function.

This considerably simplifies the work of the


program, because each piece of code can be
encoded separately, and tested separately. The
process described here is often
called decomposition.
Why do we need functions?
If a piece of code becomes so large that reading
and understating it may cause a problem,
consider dividing it into separate, smaller
problems, and implement each of them in the
form of a separate function.
Why do we need functions?
We need functions in programming for several crucial reasons:

Code Reusability
Functions allow you to write a piece of code once and use it multiple times
Instead of repeating the same code block, you can call a function whenever needed

Example:
def calculate_area(length, width):
return length * width

# Reuse the same function for different calculations


print(calculate_area(5, 3)) # 15
print(calculate_area(10, 4)) # 40
Decomposition
Python decomposition refers to breaking down a
complex problem, task, or program into smaller, more
manageable pieces. These smaller pieces can be
individual functions, modules, or even objects. By
dividing a large program into smaller parts,
decomposition helps improve code organization,
readability, reusability, and maintainability.
How functions work
•when you invoke a function,
Python remembers the place
where it happened and jumps into
the invoked function;
•the body of the function is
then executed;
•reaching the end of the function
forces Python to return to the
place directly after the point of
invocation.
Example:
def message():
print("Enter a value:", end=‘’)
message()
a = int(input())
message()
b = int(input())
message()
c = int(input())
Types of Functions
Python support two types of functions
• Built-in function
• User-defined function
Built-in function

• The functions which are come along with Python itself are
called a built-in function or predefined function.
example: range(), id(), type(), input(), eval() etc.
Example of Built in Function
Python range()
Function generates the immutable sequence of
numbers starting from the given start integer to the stop
integer.
for i in range(1,10):#range(start, stop, step)
print(i, end=' ')
# Output 1 2 3 4 5 6 7 8 9
User-defined function
Functions which are created by programmer explicitly
according to the requirement are called a user-defined
function.
Creating a Function

Use the following steps to to define a function in Python.


Use the def keyword with the function name to define a function.
Next, pass the number of parameters as per your requirement.
(Optional).
Next, define the function body with a block of code. This block of
code is nothing but the action you wanted to perform.
Syntax of creating function
def function_name(parameter1, parameter2): function_name: Function name is the name of the function.
We can give any name to function.
# function body
parameter: Parameter is the value passed to the function.
# write some action We can pass any number of parameters. Function body uses
the parameter’s value to perform an action
return value
function_body: The function body is a block of code that
performs some task. This block of code is nothing but the
action you wanted to accomplish.

return value: Return value is the output of the function.


Creating a function without
any parameters
# function
def message():
print(“hello world")
# call function using its name
message()
Creating a function with
parameters and return value
# function
def calculator(a, b):
add = a + b
# return the addition
return add
# call function
# take return value in variable
res = calculator(20, 5)
print("Addition :", res)
# Output Addition : 25
Calling a function

• Once we defined a function or finalized structure, we can call


that function by using its name. We can also call that function
from another function or program by importing it.
• To call a function, use the name of the function with the
parenthesis, and if the function accepts parameters, then pass
those parameters in the parenthesis.
Calling a function
# function
def even_odd(n):
# check number is even or odd
if n % 2 == 0:
print('Even number')
else:
print('Odd Number')
# calling function by its name
even_odd(19)
# Output Odd Number
Return Value From a
Function
In Python, to return value from the function, a return statement is
used. It returns the value of the expression following the returns
keyword.
The return value is nothing but
Return Value From a a outcome of function.
Function • The return statement ends
def is_even(list1): the function execution.
even_num = []
for n in list1: • For a function, it is not
if n % 2 == 0: mandatory to return a value.
even_num.append(n) • If a return statement is used
# return a list without any expression, then
return even_num the None is returned.
# Pass list to the function • The return statement should
even_num = is_even([2, 3, 42, 51, 62, 70, 5, 9]) be inside of the function
print("Even numbers are:", even_num) block.
Return Multiple Values
def arithmetic(num1, num2):
add = num1 + num2
In this example, we are
sub = num1 - num2 returning three values from a
multiply = num1 * num2 function. We will also see
division = num1 / num2 how to process or read
# return four values
multiple return values in our
return add, sub, multiply, division
code.
# read four return values in four variables
a, b, c, d = arithmetic(10, 2)

print("Addition: ", a)
print("Subtraction: ", b)
print("Multiplication: ", c)
print("Division: ", d)

You might also like