0% found this document useful (0 votes)
4 views35 pages

Exp1 3

The document provides an overview of Python programming functions, covering their syntax, usage, parameters, and scope. It explains the concepts of local and global variables, return statements, and recursive functions, along with examples. Additionally, it highlights the advantages and disadvantages of recursion and includes various program examples for practical understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views35 pages

Exp1 3

The document provides an overview of Python programming functions, covering their syntax, usage, parameters, and scope. It explains the concepts of local and global variables, return statements, and recursive functions, along with examples. Additionally, it highlights the advantages and disadvantages of recursion and includes various program examples for practical understanding.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 35

Department of Computer Science and Engineering (CSE)

Python Programming

Functions

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Outline

• Introduction
• Syntax and Basics of a Function
• Use of a function
• Parameters and Arguments
• Local and Global Scope of a Variable
• Return statement
• Recursive Functions

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Introduction

• Functions are common to all programming languages.


• A function is a block of related statements that performs a specific task
when called.
• Built-in functions are usually a part of Python packages and libraries,
whereas user-defined functions are written by the developers to meet
certain requirements.
• In Python, all functions are treated as objects, so it is more flexible
compared to other high-level languages.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Syntax and Basics of a Function

• Syntax of Function

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Syntax and Basics of a Function

• Keyword def marks the start of function header.


• A function name to uniquely identify it.
• Function naming follows the same rules of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function.
They are optional.
• A colon (:) to mark the end of function header.
• One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Syntax and Basics of a Function

def user( ):
print("Python Programming")
print("This is user defined function")
user( );

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Use of a function

• Suppose that you need to find the sum of integers from 1 to 10, 20 to 40 ,
and 50 to 100. If you create a program to add these three sets of numbers,
your code might look like this:
sum = 0
for i in range(1, 11):
sum = sum+i
print("Sum from 1 to 10 is", sum)
sum=0
for i in range(20,41):
sum = sum+i
print("Sum from 20 to 40 is", sum)
sum = 0
for i in range(50, 101):
sum = sum+i
print("Sum from 50 to 100 is", sum)
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Use of a function

# Using Function
def sum(x,y):
s=0
for i in range(x,y+1):
s=s+i
print("Sum of values from",x,'to',y,'is',s)
sum(1,10)
sum(20,40)
sum(50,100)
# End of Program

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Use of a function

• Functions are reusable code blocks, they only need to be written once,
then they can be used multiple times. They can even be used in other
applications, too.
• The code is usually well organized, easy to maintain and developer
friendly.
• It can support the modular design approach.
• A well-defined and thoughtfully written user-defined function can ease
the application development process.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

• A parameter is a variable defined by a method that receives a value when


the method is called.
• An argument is a value that is passed to a method when it is invoked.
# Function Program
def add_numbers(x, y, z):
a=x+y the number 1 is for the x parameter,
b=x+z 2 is for the y parameter,
c=y+z 3 is for the z parameter.
The number 1,2 and 3 are called arguments.
print(a, b, c)
add_numbers(1, 2, 3)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

• Function arguments in Python


• Positional Arguments
• When you call a function, Python must match each argument in the
function call with a parameter in the function definition.
• The simplest way to do this is based on the order of the arguments
provided. Values matched up this way are called positional arguments.
• You can use as many positional arguments as you need in your functions.
• You can get unexpected results if you mix up the order of the arguments
in a function call when using positional arguments

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

# Positional Arguments
def display(name,course,per):
print("Your name is:",name,"\nYou are enrolled for:",course,
"\nYour percentage is:",per)
display('abc','BE',81.79)
# End of Program

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

• Function arguments in Python


• Keyword Arguments
• Keyword arguments are relevant for Python function calls.
• The keywords are mentioned during the function call along with their
corresponding values. These keywords are mapped with the function
arguments so the function can easily identify the corresponding values
even if the order is not maintained during the function call.
• All the keyword arguments passed must match one of the arguments
accepted by the function. You may change the order of appearance of the
keyword.
• Multiple values for same argument are not allowed in function call.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

# Keyword Arguments
def display(name,course,per):
print("Your name is:",name,"\nYou are enrolled for:",course,
"\nYour percentage is:",per)
display(course='BE',per=81.79,name='abc')

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

• Parameter with default values


• In function's parameters list you can specify a default value(s) for one
or more arguments.
• A default value can be written in the format "argument1 = value",
therefore you will have the option to declare or not declare a value for
those arguments.
• Any number of arguments in a function can have a default value.
• Once you have a default argument, all the arguments to its right must
also have default values. i.e. non-default arguments cannot follow
default arguments.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Parameters and Arguments in a Function

• Parameter with default values


# Default Arguments
def display(name,course='ME',per='81.79'):
print("Your name is:",name,"\nYou are enrolled for:",course,
"\nYour percentage is:",per)
display(course='BE',name='abc')

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Local and Global Scope of a Variable

• There are two types of variables: global variables and local


variables.
• A global variable can be reached anywhere in the code.
• A local variable can be reached only in the area in which they are
defined, which is called scope.
• Scope of a variable is the portion of a program where the variable is
recognized. 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 you return from the function. Hence,
a function does not remember the value of a variable from its previous
calls.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Local and Global Scope of a Variable

• Accessing a local variable outside the scope will cause an error.


• If a variable with same name is defined inside the scope of function as
well then it will print the value given inside the function only and not the
global value.
• Any variable which is changed or created inside of a function is local, if it
has not been declared as a global variable. To tell Python, that you want to
use the global variable, you have to use the keyword “global”.
• The keyword global is not needed for printing and accessing. It is only
required in a function if you want to do assignments / change them.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Local and Global Scope of a Variable

#Local and Global Variable


def display( ):
x = 10 #Local Variable
print("Value inside function:",x)
#Global Variable
x = 20
display( )
print("Value outside function:",x)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Local and Global Scope of a Variable

#Local and Global Variable


x = 20 #Global Variable
def display( ):
x = 10 #Local Variable
print("Value inside function:",x)
display( )
print("Value outside function:",x)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Local and Global Scope of a Variable

#Local and Global Variable


# Global Statement
def display( ):
global x
x = 10
print("Value inside function:",x)
x=20
display( )
print("Value outside function:",x)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Return statement

• The return statement is used to return a value from the function.


• It is also used to exit a function and go back to the place from where it was
called.
• Syntax of return
• return expression_list
• If there is expression in the statement 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.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Return statement

def square(x): def square(x):


y = x ** 2 y = x ** 2
return y # return y

result = square(5) result = square(5)

print(result) print(result)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Return statement

• Write a function to compute the discriminator that returns the output


depending on the discriminator.
• If discriminator >0: Two real roots
• If discriminator=0: One Real root
• If discriminator<0: Two Complex roots

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Return statement

import math
a= eval(input("Enter value of a= "))
b= eval(input("Enter value of b= "))
c= eval(input("Enter value of c= "))
def roots(a,b,c):
disc = b**2 - 4*a*c
if disc >= 0:
print("Value of a:",a,"Value of b:",b,"Value of c:",c)
print("Discriminant",disc)
return ("r1=",(-b + math.sqrt(disc))/(2*a),"r2=",(-b - math.sqrt(disc))/(2*a))
else:
print("Value of a:",a,"Value of b:",b,"Value of c:",c)
print("Discriminant",disc)
return ('r1=',-b/(2*a),'+i',math.sqrt(disc*(-1))/(2*a),
'r2=',-b/(2*a),'-i',math.sqrt(disc*(-1))/(2*a))
print(roots(a,b,c))

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Return statement

• It is possible to return multiple values in python.


• It is also possible for a function to perform certain operations, return
multiple values and assign the returned multiple values to a multiple
variable.
# Returning Multiple Values from a Function
def compute(num):
print("Number=",num)
return num*num,num*num*num
square,cube=compute(6)
print("Square=",square, ", ", "Cube=",cube)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Return statement

# Returning Multiple Values from a Function


num=eval(input("Enter the number:"))
def compute(n):
print("Number=",num)
return num*num,num*num*num
square,cube=compute(num)
print("Square=",square,", ", "Cube=",cube)

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Recursive Functions

• Recursion is the process of defining something in terms of itself.


• A physical world example would be to place two parallel mirrors facing
each other. Any object in between them would be reflected recursively.
• A function can call other functions. It is even possible for the function to
call itself. These type of construct are termed as recursive functions.
• Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Recursive Functions

• Advantages of Recursion
• Recursive functions make the code look clean and elegant.
• A complex task can be broken down into simpler sub-problems using
recursion.
• Sequence generation is easier with recursion than using some nested
iteration.
• Disadvantages of Recursion
• Sometimes the logic behind recursion is hard to follow through.
• Recursive calls are expensive (inefficient) as they take up a lot of
memory and time.
• Recursive functions are hard to debug.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Recursive Functions

# Factorial of a number
num=int(input("Enter the number:"))
def factorial(n):
if n==0:
return 1
return n*factorial(n-1)
print(factorial(num))

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Recursive Functions

#Fibonacci series Program using Recursion


# Recursive Function Beginning
def fibo(num):
if(num==0):
return 0
elif(num==1):
return 1
else:
return(fibo(num-2)+fibo(num-1))
# End of the Function
# Fibonacci series will start at 0 and continue up to specified range
num=int(input("Enter the Range for fibonacci series:"))
# Find & Displaying Fibonacci series
for i in range(0,num):
print(fibo(i))
University Institute of Engineering (UIE)
Department of Computer Science and Engineering (CSE)

Recursive Functions

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

Programs

• Program to check if a given number is prime or not.


• Program to check a number is palindrome or not.
• Program to demonstrate the use of local and global variables.
• Program to check whether a number falls within a given range or not.
• Program to find GCD of two numbers.
• Program to calculate simple interest and compound interest.
• Program to generate BMI calculator.
• Program to return both addition and subtraction in a single return call.
• Write a function called exponent(base, exp) that returns an int value of
base raises to the power of exp.
• Program to implement binary search.

University Institute of Engineering (UIE)


Department of Computer Science and Engineering (CSE)

THANKS…..

University Institute of Engineering (UIE)

You might also like