0% found this document useful (0 votes)
2 views20 pages

Python Functions: Types and Usage

The document provides an overview of functions in Python, explaining their advantages, types, and how to define and call them. It details built-in, module-defined, and user-defined functions, along with examples of different function categories based on parameters and return values. Additionally, it covers function arguments, including positional, default, and keyword arguments, and discusses the scope and lifetime of variables within functions.

Uploaded by

Tripti Sharma
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)
2 views20 pages

Python Functions: Types and Usage

The document provides an overview of functions in Python, explaining their advantages, types, and how to define and call them. It details built-in, module-defined, and user-defined functions, along with examples of different function categories based on parameters and return values. Additionally, it covers function arguments, including positional, default, and keyword arguments, and discusses the scope and lifetime of variables within functions.

Uploaded by

Tripti Sharma
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

Working with Function

In Python, function is a group of related statements that perform a specific task.


Note: Functions are also known as methods.

Advantages of functions
1. Using functions we can divide a large program into a number of functions/modules.
2. Understanding the program becomes easy
3. Debugging the program becomes easy
4. Reusability of the code increases: function once written can be used again and again as
and when required.
5. A function can be called any number of times.

Types of Functions
Basically, we can divide functions into the following three types:
1. Built-in functions – Functions that are built into Python
2. Function defined in Modules
3. User-defined functions – Functions defined by the users themselves

Built-in function: Functions defined in the Python library. The Python interpreter has a number
of functions that are always available for use. These functions are called built-in functions. For
example print(), input(), int(), float(), len(), ord() etc. In Python 3.8, there are 69 built-in
functions.
Module defined function: Ex: sin(), cos(), mean(), randint() etc. Whenever we are required to
use any function defined inside a particular module, then before using that function, we have
to import that module in our program. Example: import math

User-defined function: Functions that are defined by users to do certain specific task are
referred to as user-defined functions.
User-Defined Python Functions
How to define a function
A user-defined python function is created using the keyword "def".
Syntax of Function
def functionName(Parameters):
#statements
#statements
return
Above shown is a function definition which consists of following components:
1. def- The keyword "def" marks the start of the function header.
2. function_name- A function name helps us to identify the function. The function
name should follow the rules of writing identifiers in Python.
3. Parameters- These help us to pass values to a function. These are optional.
4. colon(:)- This marks the end of the function header.
5. Statements- One or more valid python statements that make up the function
body. Statements must have the same indentation level.
6. return - An optional return statement to return a value from the function.

Example:
def hello():
print("We are in hello function")

Calling/Invoking a function
A user-defined function does not execute on its own. It must be called in somewhere, this
process is known as calling or invoking. A user-defined function can be invoked like any other
function in Python by writing the function name and passing the parameters inside the
brackets(). If there are no parameters, keep the brackets empty. If a function is not called, it
won’t be executed.

To use any type of function we need to write a function call statement in Python program.
Syntax of function call:
Function_Name(arguments)

example of function call:


hello()

Structure of a Python Program with Function

Let us understand the Flow of execution of a program with functions

⮚ The order in which statements are executed is called the flow of execution
⮚ Execution always begins at the first statement of the program.
⮚ Statements are executed one at a time, in order, from top to bottom.
⮚ Remember that statements inside the function are not executed until the function is
called.
⮚ Whenever we encounter the function call, Instead of going to the next statement, the
control flow jumps to the header of the function definition, executes all the statements
inside the function, and then comes back to the caller. Then, we execute the statement
next to function call

Q. Consider the following code and write the Flow of execution of this.

1. def power(b,p):
2. y=b**p
3. return y
4. def calcsquare(x):
5. a=power(x,2) # function call
6. return a
7. n=8
8. result=calcsquare(n)+power(4,3) # two function calls
9. print(result)

Ans:

1->4->7->8->4->5->1->2->3->5->6->8->1->2->3->8->9

Note: we may use the words “parameter” and “arguments” interchangeably though they

differ slightly in meaning.

Argument: It is a value that is passed to the function when it is called. It can be one of these value types:-

literals or variables or expressions.

Parameter: It is a variable provided in the parentheses when we write function header It must be variable
only.
User defined function can be any of the following type:
1. without parameters, without return statement
2. without parameters , with return statement
3. with parameters, without returning any result
4. with parameters, with returning result

Note: In Python a function can return multiple values (Very Important)

Example of Function (category 1)


1. Without parameters/arguments, without returning result
In this, we do not pass any arguments to the function and the function does not return any value.

Example 1: Write a python script using functions to calculate and print square of a number
def square(): # no parameters
a=int(input("Enter any no "))
b=a*a
print("Square = ",b)
# no return stmt

square() #function call

Output:
Enter any no 7
Square = 49

Example 2: Write a python script using function to calculate and print cube of a number

#function definition
def cube():
a=int(input("Enter any no "))
b=a*a*a
print("Cube = ",b)
cube() #function call

Output:
Enter any no 5
Cube = 125

Example 3: Write a python script using a function to take input for two numbers, calculate and
print their sum, product and difference.
Method:1 Using Single Function

#function definition

def calculate():
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
s=a+b
d=a-b
p=a*b
print("Sum = ",s)
print("Diff = ",d)
print("Prod = ",p)

calculate() #function calling

Enter 1st no 15
Enter 2nd no 8
Sum = 23
Diff = 7
Prod = 120

Method:2 (Using Multiple functions)

#function definition

def sum1():
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
s=a+b
print("Sum = ",s)

def diff():
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
d=a-b
print("Difference = ",d)

def prod():
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
p=a*b
print("Product = ",p)
#function calling
sum1()
diff()
prod()

Output:
Enter 1st no
10 Enter 2nd
no 20 Sum = 30
Enter 1st no 20
Enter 2nd no 8
Difference = 12
Enter 1st no 4
Enter 2nd no 7
Product = 28

Example of Function (category 2)


Without argument/parameter, with returning result using return statement
The return statement is used to exit a function and go back to the place from where it was called.

Syntax of return
return
or
return expression
or
return expression1, expression2, expression3, …….
This statement can contain expression which gets evaluated and the value is returned. If there is
no expression in the statement or the return statement itself is not present inside a function,
then the function will return the None object.
Example 4: Write a Python program using function to find the biggest of three numbers.
Execution Output:

Example 5: Write a python program using function to take input for 2 numbers, returns the sum
of both.
def Sum():
x=int(input("Enter first value "))
y=int(input("Enter second value "))
s=x+y
return s
# main
print(Sum())

Note: In place of print(Sum()) above, we can give the following two commands:
r=sum()
print(r)

Function returning multiple values


In python, we can return multiple values from a function.
Example 6: Write a python using function to take input for 2 numbers, calculate and returns sum,
difference, product and quotient.
def calc():
x=ini(input("Enter first value "))
y=int(input("Enter second value "))
return x+y, x-y, x*y, x//y
# main
s, d, p, q=calc()
print('Sum=",s)
print("Difference=',d)
print("Product=",p)
print("Quotient=",q)

Example of function (category 3)


With argument/parameter, without returning result
In this we pass arguments to the function, but the function does not return any value.
First let us discuss about Argument and Parameter
Example 7: Write a Python program using function to find the biggest of three numbers.

Execution Output:

Example 7: Python script to calculate and print sum of two numbers


#function definition
def sum(p,q):
s=p+q
print("Sum = ",s)

#function calling
a=int(input("Enter 1st no "))
b=int(input("Enter 2nd no "))
sum(a,b)

Output:
Enter 1st no 10
Enter 2nd no 20
Sum = 30

Example 8: Python script to calculate and print square of a number

#function definition
def square(n):
s=n*n
print("Square = ",s)

#function calling
a=int(input("Enter 1st no "))
square(a)

Output:
Enter 1st no 2
Square = 4

Example 9: Python script to calculate and print cube of a number

#function definition
def cube(n):
s=n*n*n print("Cube = ",s)

#function calling
a=int(input("Enter 1st no "))
cube(a)

Output:
Enter 1st no 5Cube = 125

Example 10: Python script to calculate and print square and cube of a number (Multiple
functions)

#function definition
def square(n):
s=n*n
print("square = ",s)
def cube(n):
s=n*n*n
print("Cube = ",s)

#function calling
a=int(input("Enter 1st no "))
square(a)
cube(a)

Output:
Enter 1st no 5
square = 25
Cube = 125
Example of a function (category 4)
Functions with arguments/parameters and returning value

In this we pass arguments to the function and function also returns a value.
Example 11: Write a Python program using function to find the biggest of three numbers.

Execution Output:

Example 11: Write a Python program using function to find the prime number.

# Function to find out prime number


def prime(x):
s=0
for i in range(1,x+1):
if x%i ==0:
s+=1
if s==2:
return "Prime"
else:
return "Not Prime"

# main
n=int(input("Enter an integer value "))
print(prime(n))

Example 12: Write a Python program using function to calculate area of a rectangle.
#function definition
def rec_area(l,b):
ar=l*b
return(ar)

l=int(input('Enter length of a rectangle: '))


b=int(input('Enter breadth of a rectangle: '))
area=rec_area(l,b)
print('Area of a rectangle = ',area)

Output:
Enter length of a rectangle: 20
Enter breadth of a rectangle: 50
Area of a rectangle = 1000

Example 13: Write a program to calculate square and cube of a number. (returning multiple
values)
#function definition
def cal(a):
sq=a*a
cu=a*a*a
return(sq,cu)

n=int(input('Enter any number: '))


s,c=cal(n)
print('Square of ',n,' =',s)
print('Cube of ',n,' =',c)

Output:
Enter any number: 5
Square of 5 = 25
Cube of 5 = 125

Example 14: Write a program to calculate sum, difference, product, and quotient of two integer
numbers.
def calc(x,y):
return x+y, x-y, x*y, x//y
# main
a=int(input("Enter first value "))
b=int(input("Enter second value "))
s, d, p, q=calc(a,b) # unpack the tuple
print("Sum= ",s)
print("Difference= ",d)
print("Product= ",p)
print("Quotient= ",q)

Type of arguments

While calling a function 3 types of actual arguments are allowed in Python. They are as follows:
1. Positional arguments (Required or Mandatory arguments)
2. Default Parameters
3. Keyword (named) arguments

[Link] Arguments: Arguments passed to a function in correct positional order. In this


the arguments must be provided for all parameters. The values of arguments are matched with
parameters position wise.
def product(x,y):
p=x*y
print("Product= ",p)
# main
product(17,9)

Output:
Product= 153
[Link] Parameters: Function parameters can have default values for positional arguments.
We can provide a default value to a parameter in function header, by using the assignment
operator (=). Here is an example.
Example 1:
def greet(name, msg = "Good morning!"): # note msg is default
print("Hello",name + ', ' + msg)

greet("Ekta") # call 1, Ekta mapped to name


greet("Ekta","How do you do?") # call 2
In this function, the first parameter name does not have a default value and is required
(mandatory) during a call.
On the other hand, the parameter msg has a default value of "Good morning!". So, it is optional
during a call. If a value is provided, it will overwrite the default value.
Any number of parameters in a function can have a default value. But once we have a default
parameter in function header, all the parameters to its right must also have default values.
This means to say, non-default parameters cannot follow default parameters. For example, if we
had defined the function header above as:

def greet(msg = "Good morning!", name):


We would get an error as:
SyntaxError: non-default argument follows default argument

Example 2:
#function definition
def cal(n1=10,n2=20,n3=30,n4=40):
s=n1+n2+n3+n4
print("Sum = ",s)

#function calling
cal()
cal(1)
cal(1,2)
cal(1,2,3)
cal(1,2,3,4)

Output:
Sum = 100
Sum = 91
Sum = 73
Sum = 46
Sum = 10

Keyword (named) Arguments: Python allows functions to be called using keyword [Link]
keyword argument, we need the name of the argument as well in function call. When we call
functions in this way, the order (position) of the arguments can be changed. Positional arguments, if
any, always come before keyword argument in a function call
example 1:
def sum1(a, b, c):
return a+b

#function calling
sum1(b=10, c=2, a=3) #order of arguments does not matter within keyword arguments
sum1(10, c=5, b=12) # keyword arguments after positional arg “10”
sum1(a=20, c=30, 90) # ERORRR, KEYWORD ARGS CAN’T COME BEFORE THE POSITIONAL ARG

example 2

def greet(name, msg):


print("Hello", name, msg)

#function calling
greet(name = "Ekta",msg = "How do you do?") #call 1
greet(msg = "How do you do?",name = "Ekta") # call 2
greet(name="Ekta",msg = "Hope all is fine") # call 3
greet("Ekta",msg = "How do you do?") # position and keyword both

As we can see, we can mix positional arguments with keyword arguments during a function call.
But we must keep in mind that keyword arguments must follow positional arguments. Having a
positional argument after keyword arguments will result into errors. For example the function
call as follows:

greet(name="Ekta","How do you do?") #error

Will result into error as:


SyntaxError: non-keyword arg after keyword arg

Scope and Lifetime of variables


Scope of a variable is the portion of a program where the variable can be accessed. Parameters
and variables defined inside a function is not visible from outside. Hence, they have a local
scope.
Lifetime of a variable is the period throughout which the variable exits in the memory. The
lifetime of variables inside a function is as long as the function executes.
They are destroyed once we return from the function. Hence, a function does not remember
the value of a variable from its previous calls.
Local Scope
A variable created inside a function belongs to the local scope of that function, and can only be
used inside that function. Local variables inside the function can be created using “= “ to sign. pls
note that Parameters in the function header are automatically local to function.
Global Scope
A variable created in the main body of the Python code is a global variable and belongs to the
global scope. Global variables are available from within any scope, global and local.

⮚ When we create a variable inside a function, it’s local by default.


⮚ When we define a variable outside of a function, it’s global by default. You don’t have to
use global keyword.

Example 1:
def myfun():
a=15 //local variable is created when we use = sign
print(a)

a=95 // global variable


print(a)
myfun()
print(a)
Output:
95
15
95

In the above program variable a is declared in local as well as global scope. But the value of a in
both the region is different. The variable ‘a’ in myfun() is local to this function but outside this
function variable “a” is a global variable.

Example 2:
def calsum(x,y):
z=x+y
return(z)

num1=int(input("Enter first no.: "))


num2=int(input("Enter sec. no.: "))
s=calsum(num1,num2)
print("Sum of given nos = ",s)
Output:
Enter first no.: 10
Enter sec. no.: 20
Sum of given nos =
30

In the above program three variables-num1, num2 and s are global variables while x, y, z which
are declared inside the function are local variables( local to the function calsum()).

Example 3:
#function definition
def calsum(x,y,z):
s=x+y+z
return(s)
def average(a,b,c):
s1=calsum(a,b,c)
return(s1/3)
#main
num1=int(input('Enter first no.: '))
num2=int(input('Enter sec. no.: '))
num3=int(input('Enter third no.: '))
av= average(num1,num2,num3) #function calling
print('Average of given nos = ',av)

Output:
Enter first no.: 50
Enter sec. no.: 60
Enter third no.: 10
Average of given nos = 40.0

In the above program we can see –


Local environment of calsum() function where x, y, z and s are its local variables.
Local environment of average() function where a, b, c and s1 are its local
variables.
Global environment where num1, num2, num3 and av are global variables.

Altering the Global values inside the function


we know that we can access global variables inside a function as shown below

def function():
print(a)
# it will print global a, since no local variable “a” has been created using “=” sign
# global variables are accessible inside function
a=10 # global a
function() # function call

Output: 10

However, in order to change a global variable inside a function, we need to declare it global first,
using the global keyword as shown below

def function():
global a # In this function, “a” will refer to global a only
a=15 # No local variable with name “a” created. Global a will be changed
print(a)
a=10 # global a
print(a)
function() # function call
print(a) # after function call, a is changed
OUTPUT:
10
15
15

Consider the next example, in which global a is not changed as we are not using global keyword
(VERY IMP)

def function():
a=15 # local variable a created
print(a)

a=10 # global a
print(a)
function() # function call
print(a)

OUTPUT:
10
15
10

Consider the next example, to clear your doubts 🙂


def function():
global b # Global b declared
b=5 # changes done to global b
a=15 # local variable a created
print(a,b)
a=100 # global a
b=200 # global b
print(a, b)
function() # function call
print(a, b)

OUTPUT:
100 200
15 5
100 5

Mutable/Immutable properties
In Python, integer, float, string and tuple are immutable objects. List, dict and set fall in the
mutable object category. This means the values of list or a dict is changed (in place) inside the
function, then it will be reflected outside the function also

Example-1:
def change(L):
[Link](5) # inplace change in list
print(L)

List=[2,3,4]
change(List)
print(List)

output:
[2,3,4,5]
[2,3,4,5]

Example-2:
def change(L):
L=[9,8,7] # reassignment using “ = “ means creating a new local variable L
print(L)

List=[2,3,4]
change(List)
print(List)

output:
[9,8,7]
[2,3,4,5]
You may go through the following examples to practice functions

Q1. Write a Python program with function to find the


product of all the numbers in a list.
def product(numbers):
p = 1
for i in numbers:
p *= i
return p

# main
lst=[]
n=int(input("Enter how many values "))
for i in range(n):
a=int(input("Enter value "))
[Link](a)

print("Original list ")


print(lst)
print("Product=",product(lst)) # pls note function call, product(lst)

Q2. Write a Python function that accepts a string as parameter and calculates the number of
uppercase letters and lower-case letters.
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if [Link]():
d["UPPER_CASE"]+=1
elif [Link]():
d["LOWER_CASE"]+=1
else:
pass
return(d["UPPER_CASE"], d["LOWER_CASE"])

# main
str1=input("Enter string”)
print("Original string : ",str1)

r1,r2=string_test(str1) # function call


print("No. of Uppercase characters : ",r1)
print("No. of Lowercase characters : ",r2)

Q3. Write a Python function that takes a list and returns a new list with unique elements of the
first list.

def unique_list(l):
x = []
for a in l:
if a not in x:
[Link](a)
return x

# main
lst=[]
n=int(input("Enter how many values "))
for i in range(n):
a=int(input("Enter value "))
[Link](a)
print("Original value ")
print(lst)
print("Unique values=",unique_list(lst)) #note function call

Q4. Write a Python program using function to print the even numbers from a given list.
def even_num(l):
even = []
for a in l:
if a % 2 == 0:
[Link](a)
return even

# main
lst=[]
n=int(input("Enter how many values "))
for i in range(n):
a=int(input("Enter value "))
[Link](a)
print("Original value ")
print(lst)
print("Even values=",even_num(lst)) #note function call

You might also like