Python Function |Functions in Python

A function is block of code that performs a specific task. It helps us to organize code, avoid repetition, and make programs easier to read and maintain. Functions are fundamental to structuring programs and promoting code reusability and modularity. Function improves a program’s clarity and readability.

Advantages of using Function / Benefits of using Function

Code Reusability – Write once, use multiple times. A function can be used to keep away from rewriting the same block of codes which we are going use two or more locations in a program. This is especially useful if the code is long or complicated. A function once created can be called countless number of times.

Increases program readability– The length of the source program can be reduced by using/calling functions at appropriate places so program become more readable.

Modularity – Breaks down big complex problems into smaller, manageable parts. Functions helps to divide the entire code of the program into separate blocks, where each block is assigned with a specific task.

Easy maintenance – Makes code easier to understand, debug and modify. Changes in one function reflect everywhere it’s used.

Understandability: use of Functions makes the program more structured and understandable by dividing the large set of codes into functions

Types of Functions in Python

Built-in Function: 

Built-in Functions are the predefined functions that are already available in python. Ready to use functions which are already defined in python and the programmer can use them whenever required are called as Built-in functions. Python has many built in functions like print(), input(), sum(), max(), min() etc.

Example:

#Program to calculate square of a number

a = int(input(“Enter a number: “))
b = a * a
print(f”The square of {a} is {b}”)

Output:

Enter a number: 5
The square of 5 is 25

In the above program input(), int() and print() are the built-in functions.

Functions defined in Modules: 

These Functions are defined inside Python modules. In order to use these functions, the programmer need to import the specific module into the program then functions defined in the module can be used. A module in Python is a file that contains a collection of related functions. To use a module, we need to import the module. To call a function of a module, the function name should be preceded with the name of the module with a dot(.) as a separator. The syntax is as shown below:

modulename.functionname()

Example:

import math
s=math.sqrt(36)
print(s) 

Output: 6.0

User-defined Functions: 

Functions that are defined by the programmer to perform a specific task is called as User Defined Functions. We can create our own functions based on our requirements. We can define as many functions as desired in program. Functions name should be unique.

We can make a function to put some commonly or repeatedly done tasks together and instead of writing the same code again and again for different inputs, we can do the function calls to reuse code contained in it over and over again.

Defining a Function (Creating a Function):

Functions are defined using the def keyword, followed by the function name, parentheses (), and a colon ( : ). The function body (code block belonging to the function) is indented. The programmer can define as many functions as desired while writing the code.

Example:

def Hello():

 print(“Hello! Friends”) 

Here, def keyword is used to create the function. Hello() is name of the function.

Elements in Function Definition

  • Function Header: The first line of the function definition is called function header. The function header starts with the keyword def, and it also specifies function name and function parameters. The header ends with colon ( : ).

   def sum(a,b):     #function Header

  • Parameter: Variables that are mentioned inside parenthesis ( ) of the function Header.
  • Function Body: The set of all statements/indented-statements beneath the function header that perform the task for which the function is designed for.
  • Indentation: All the statements inside the function body should be indented.
  • Return statement: A function may have a return statement that is used to returning values from functions.

Calling a Function:

To execute the code within a function, we need to call the function. A function executes only when it is being called. After defining a function, we can call it by using the name of the function followed by parenthesis. A function must be defined before the function calling.

Example:

Hello() # calling Hello() function

Example of a Program using Function:

def display():
    for i in range(10):
        print(“*”,end=’ ‘)
#Function call
display()

display()

Output:

* * * * * * * * * *

* * * * * * * * * *

Function Parameters and Arguments

Parameters are the variables listed inside the parentheses in the function definition. Arguments are the values that is passed to the function when it is called.

Parameters are also known as Formal Parameters, and arguments are also known as Actual Parameters. Formal parameters are always variables, and have data types associated with them when they are declared. Multiple parameters are separated by comma. Actual parameters can be numbers and do not need to have data types. When a function is called, the actual parameters are assigned to the corresponding formal parameters in the function definition.

Example:

def greet(name):  #’name’ parameter
    print(f”Hello, {name}!”)
greet(“Suraj”)  # “Suraj” is an argument

Output:

Hello, Suraj!

Function with Return Value:

Functions in python can return back values/variables  from the function to the place from where the function is called using return statement. return statement terminates the function execution if it is encountered.

Example:

def add_num(a,b):    

 return a+b

sum=add_num(10,20)         

print(f”Result : {sum}”)

Output:

Result: 30

Number of Arguments:

A function must be called with correct number of arguments. If the function has 2 arguments, we have to call the function with 2 arguments, not more and not less.

Example:

def name(fname,lname):

 print(fname, “     “ , lname)

name(“Eliza”, “Begum”)

Output:

Eliza Begum

Passing a List as an Argument

We can send any data types of argument to a function (string, number, list, dictionary etc.), and it will be treated as the same data type inside the function. e.g. if we send a List as an argument, it will still be a List when it reaches the function:

Example:

def List(food):

 for x in food:

  print(x,end=’ ‘)

fruits=[“mango”, “apple”, “orange”]

List(fruits)

Output:

mango apple orange

Types of Arguments:

Python supports 4 types of parameters/formal arguments

  1. Positional Argument
  2. Default Argument
  3. Keyword Argument
  4. Variable length argument

Positional Arguments:

Arguments passed in correct positional order. When function call statement must contain the same number and order of arguments as defined in the function definition, then the arguments are referred as positional argument. Arguments passed in the same order as the parameters are defined in the function header.

Example:

def details(name,roll):

 print(“Hi, I am ”, name)

 print(“My rollno is: ”,roll)

details(“Eliza”,1)         #Correct output

details(1, “Eliza”)   #Incorrect Output 

Output:

Hi, I am Eliza
My rollno is: 1
Hi, I am 1
My rollno is: Eliza

Default Arguments:

Default values can be assigned to parameter in function header while defining a function, these default values will be used if the function call doesn’t have matching arguments as function definition.

Default arguments in Python allow the assignment of a default value to a function parameter within its definition. This default value is used if the corresponding argument is not provided during the function call.

Example:

def greet(name, message=”Hello”):
    print(f”{message}, {name}!”)

# Calling with default message
greet(“Riyan”)

# Calling with a custom message
greet(“Raktim”, “Hi”)

Output:

Hello, Riyan!
Hi, Raktim!

Keyword Arguments:

Python allows to call a function by passing the arguments in any order, in this case the programmer have to specify the names of the parameter in function call.  Arguments passed by explicitly naming the parameter in the function call, allowing for flexible argument order.

Example:

def student(fname,lname):

 print(fname,lname)

student(lname=“Begum”, fname=“Eliza”)

Output:

Eliza Begum

Variable-Length Arguments:

Variable Length  Argument in python permits to pass multiple values to a single parameter. The variable length argument precedes  the symbol ‘*’ in the function header of the function call.

Example:

def findsum(*x):
    sum=0
    for i in x:
        sum=sum+i
    print(f”Sum of numbers is: {sum}”)
findsum(2,5,3)
findsum(2,6,3,8,4,7,9)

Output:

Sum of numbers is: 10

Sum of numbers is: 39

Types of User-Defined Functions (based on argument and return value combinations)

User-defined functions in Python can be categorized into four types based on whether they accept arguments and whether they return a value:

Function with No Arguments and No Return value

These functions perform an action but do not require any input data and do not explicitly send back any result. They primarily execute a block of code.

Example:

def add():
    a=int(input(“Enter 1st number: “))
    b=int(input(“Enter 2nd number: “))
    c=a+b
    print(f”The sum is: {c}”)
add()

Output:

Enter 1st number: 20
Enter 2nd number: 30
The sum is: 50

Function with Arguments but No Return value.

These functions accept input data (arguments) to perform an action, but they do not explicitly return a value.

Example:

def add(a,b):
    c=a+b
    print(f”The sum is: {c}”)

x=int(input(“Enter 1st number: “))
y=int(input(“Enter 2nd number: “))
add(x,y)

Output:

Enter 1st number: 10
Enter 2nd number: 20
The sum is: 30

Function with No Arguments but with a Return value

These functions do not require any input but compute and return a result. They are often used to generate a specific value.

Example:

def add():
    a = int(input(“Enter 1st number: “))
    b = int(input(“Enter 2nd number: “))
    c = a + b
    return c
sum=add()
print(f”The sum is: {sum}”)

Output:

Enter 1st number: 10
Enter 2nd number: 20
The sum is: 30

Function with Arguments and with a Return Value

These functions accept input data (arguments) and compute a result, which they then return. This is a common and versatile type of function used for calculations or data transformations.

Example:

def add(a,b):
    c=a+b
    return c
x=int(input(“Enter 1st number: “))
y=int(input(“Enter 2nd number: “))
z=add(x,y)
print(f”The sum is: {z}”)

Output:

Enter 1st number: 10
Enter 2nd number: 20
The sum is: 30

User-Defined Functions with multiple return values:

In Python, user-defined functions can return multiple values by separating them with commas in the return statement.

Example-1:

def calculate(num):
 min_val = min(num)
 max_val = max(num)
 avg_val = sum(num) / len(num)
 return min_val, max_val, avg_val
data = [10, 20, 30, 40, 50]
minimum, maximum, average = calculate(data)
print(f”Minimum: {minimum}”)
print(f”Maximum: {maximum}”)
print(f”Average: {average}”)

Output:

Minimum: 10

Maximum: 50

Average: 30.0

Example-2

def calculate(a,b):
    add=a+b
    sub=a-b
    mul=a*b
    div=a/b
    return add,sub,mul,div
x=int(input(“Enter 1st number: “))
y=int(input(“Enter 2nd number: “))
a,s,m,d=calculate(x,y)
print(f”The sum is: {a}”)
print(f”The difference is: {s}”)
print(f”The product is: {m}”)
print(f”The quotient is: {d}”)

Output:

Enter 1st number: 12

Enter 2nd number: 4

The sum is: 16

The difference is: 8

The product is: 48

The quotient is: 3.0

Scope of Variables:

All variables in a program may not be accessible at all locations in that program. This depends on where we have declared a variable. The scope of a variable determines the portion of the program where we can access a particular identifier. There are two basic scopes of variables in Python –

  • Global variables
  • Local variables

A variable that has global scope is known as a global variable and a variable that has a local scope is known as a local variable.

Global Variables:

In Python, a variable that is defined outside any function is known as a global variable. Global variables are accessible throughout the program. The global keyword can be used to modify a global variable within a function. Any change made to the global variable will impact all the functions in the program where that variable can be accessed.

Example-1:

x = 20 # Global variable

def my_function():
    y=x+50
    print(x)
    print(y)
my_function()
print(x)

Output:

20
70
20

Example-2:

global_var = 10
def modify_global():
    global global_var
    global_var = 20
modify_global()
print(global_var)        

Output:

20

Local Variables:

A variable that is defined inside any function is known as a local variable. It can be accessed only in the function where it is defined. It exists only till the function executes.

Example:

def my_function():
    x = 10  # Local variable
    print(x) 
my_function()
print(x)  # This will raise an error

Key Concepts Related to Functions:

Function Definition:

The process of creating a function using def, specifying its name, parameters, and the code block it executes.

Function Call/Invocation:

Executing a defined function by writing its name followed by parentheses containing any required arguments.

Parameters:

Variables listed in the function definition’s parentheses that receive values passed during a function call. These are also known as formal parameters or formal arguments.

Arguments:

The actual values passed to a function during its call. These are also known as actual parameters or actual arguments.

Return Statement:

Used to send a value back from the function to the caller. A function can return a single value, multiple values (as a tuple), or nothing (in which case it implicitly returns None).

Flow of Execution:

The order in which statements are executed during a program run, including the transfer of control when functions are called and return.

Important points to remember:

  • A function is a block of code which only runs when it is called.
  • We can pass data(input), known as parameters into a function.
  • A function can return data (value) as a result.
  • a function may or may not have parameters. Also, a function may or may not return a value.
  • Function header always ends with a colon (:).
  • Function name should be unique.

Programming Example of Function

1. Write a program to add two numbers using function.

Solution:

def add():
 a,b=10,20
 c=a+b
 print(f”The sum is: {c}”)
add()

Output:

The sum is: 30

OR

def add():
    a=int(input(“Enter 1st number: “))
    b=int(input(“Enter 2nd number: “))
    c=a+b
    print(f”The sum is: {c}”)
add()

add()

Output:

Enter 1st number: 10

Enter 2nd number: 20

The sum is: 30

Enter 1st number: 100

Enter 2nd number: 450

The sum is: 550

2. Write a program to add two numbers using function with argument.

Solution:

def add(a,b):

 sum=a+b

 print(“Sum: ” , sum)

add(10,20)

add(250,550)

Output:

Sum:  30

Sum:  800

OR

def add(a,b):

 return a+b

sum=add(100,200)

print(“Sum: ” , sum)

Output:

Sum:  300

OR

def add(a,b):
    c=a+b
    print(f”The sum is: {c}”)
x=int(input(“Enter 1st number: “))
y=int(input(“Enter 2nd number: “))
add(x,y)

Output:

Enter 1st number: 10

Enter 2nd number: 20

The sum is: 30

3. Write a Python program to find square of a number.

Solution:

def find_sq(n):
    result=n*n
    return result
sq=find_sq(4)
print(f”Square: {sq}”)

Output:

Square: 16

4. Write a program to calculate and display the area of a rectangle. (Formula: Area of rectangle=length× breath).

Solution:

def area():
    l=int(input(“Enter length: “))
    b=int(input(“Enter breadth: “))
    a=l*b
    print(f”Area of the rectangle is : {a}”)
area()

Output:

Enter length: 7

Enter breadth: 3

Area of the rectangle is: 21

OR

def area(l, b):

 area = l*b

 return area

a=area(7,3)

print(f”Area of the rectangle is: {a}”)

Output:

Area of the rectangle is: 21

5. Write a program to find the area of a circle. (Formula: πr2, r is radius)

Solution:

def area(r):

 pi=3.142

 return pi*r*r

print(“Area is: “, area(5))

Output:

Area is:  78.55

6. Write a program to find maximum of two number.

Solution:

def maximum(a,b):

 if(a>b):

  return a

 else:

  return b

print(“Maximum number: “, maximum(6,2))

Output:

Maximum number:  6

OR

a,b=6,2

maximum=max(a,b)

print(“Maximum Number: “,maximum)

Output:

Maximum Number:  6

7. Write a program in Python to check whether the number passed as an argument to the function is even or odd.

Solution:

def evenOdd(x):

 if(x%2==0):

  print(“Even Number”)

 else:

  print(“Odd Number”)

evenOdd(8)

evenOdd(7)

Output:

Even Number

Odd Number

8. Write a program to find the largest numbers stored in a list.

Solution:

def large(x):
 m=0
 for i in x:
  if(i>m):
   m=i
 print(f”Largest number: {m}”)
L=[12,34,56,23,98]
large(L)

Output:

Largest number: 98

9. Write a program to find the factorial of a number using function.

Solution:

def fact(x):
    f=1
    for i in range(x,0,-1):
        f=f*i
    print(f”Factorial: {f}”)
n=int(input(“Enter a number: “))
fact(n)

Output:

Enter a number: 5

Factorial: 120

10. Write a python program to print Fibonacci Series.

Solution:

def fib(n):

 a,b = 0,1

 while(a<n):

  print(a, end= ‘ ’)

  a,b = b,a+b

fib(50)

Output:

0 1 1 2 3 5 8 13 21 34

11. Write a program to calculate average of 5 numbers stored in a list.

Solution:

def avg(x):
    s=0
    for i in x:
        s=s+i
    print(f”Average: {s/5}”)
L=[10,20,30,40,50]
avg(L)

Output:

Average: 30.0

12. Write a program in Python to determine the season based on a given month number.

Solution:

def find_season(month_no):
 if month_no in[12, 1, 2]:
  return “Winter”
 elif month_no in[3, 4, 5]:
  return “Spring”
 elif month_no in [6, 7, 8]:
  return “Summer”
 elif month_no in [9, 10, 11]:
  return “Autumn”
 else:
  return “Invalid Month Number”
month_input=int(input(“Enter the month number (1-12): “))
season=find_season(month_input)
print(f”The season for month {month_input} is: {season}”)

Output:

Enter the month number (1-12): 4

The season for month 4 is: Spring

13. Write a python program that prints the calendar for a given month and year.

Solution:

    import calendar
    year=int(input(“Enter the year: “))
    month=int(input(“Enter the month: “))
    print(calendar.month(year,month))

    Output:

    Enter the year: 2025

    Enter the month: 8

    Leave a Comment