0% found this document useful (0 votes)
2 views

User Defined Functions -Notes

User-defined functions in Python are created by programmers using the 'def' statement, allowing for custom tasks. They can have parameters and return values, with various types including functions with no arguments, functions with arguments but no return value, and functions that return values. The document also includes examples and activities to illustrate the concepts of defining and using functions.

Uploaded by

kashisajitv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

User Defined Functions -Notes

User-defined functions in Python are created by programmers using the 'def' statement, allowing for custom tasks. They can have parameters and return values, with various types including functions with no arguments, functions with arguments but no return value, and functions that return values. The document also includes examples and activities to illustrate the concepts of defining and using functions.

Uploaded by

kashisajitv
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

USER DEFINED FUNCTIONS IN PYTHON

INTRODUCTION
• These are the functions defined by the programmer.
• Functions that we define ourselves to do some special task are called user-defined
functions.
• It is created or defined by the def statement followed by the function name,
parenthesis() and colon(:).
• Syntax:

def function_name([Parameters]): # Function Header


<statements> # Function Definition
<[Statements]> # Function Body
COMPONENTS OF FUNCTION DEFINITION
• Keyword def marks the start of the function header.
• Function name must follow the rules for identifiers.
• It may or may not contain parameters/arguments.
• Colon(:) marks the end of the function header.
• Statement after colon begin with four spaces called indentation.
• One or more statements constitute the function body.
• An optional return statement to return a value from the function.
• Function must be called/invoked to execute its code.
• All statements within the same block must have same indentation.
EXAMPLE
def display(): # Function Header
print(“I am learning Python Programming”) # Function Body
display() # Function Calling/Invoking

Output
I am learning Python Programming

• In a program, we can define any number of functions we want.


• If the indentation of function body is wrong, it will show a Syntax Error:
“expected an indented block”
EXAMPLE
def add():
n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
s=n1+n2
print(“Sum is”,s)
add()
Output
Enter First Number:10
Enter Second Number:40
Sum is 50
PARAMETERS & ARGUMENTS IN FUNCTIONS
• Parameters are the variables provided in the parentheses when we write
function definition.
• These parameters are called Formal Parameter/Formal Argument.
• Arguments are the values/variables provided in the function call/invoke
statement and passed to the variables of formal parameters of the function.
• These arguments are called Actual Argument/Actual Parameter.
• Example 1:
def SI (p , r, t): Formal Parameter
print(p*r*t)
SI(40000, 30, 5) Actual Parameter
PARAMETERS & ARGUMENTS CONTD…
• Example 2:
def SI(p,r,t):
print(p*r*t)
a=int(input("Enter Principle Amount:"))
b=int(input("Enter Rate of Interest:"))
c=int(input("Enter Time in Years:"))
SI(a,b,c)
OR
def SI():
p=int(input("Enter Principle Amount:"))
r=int(input("Enter Rate of Interest:"))
t=int(input("Enter Time in Years:"))
print(p*r*t)
SI()
PARAMETERS & ARGUMENTS CONTD…
• The number and type of arguments should be same as mentioned in parameter list.
• If the number of formal arguments and actual arguments differs, it will raise an error.
• Arguments can be one of these value types- literals or variables or expressions whereas
parameters have to be some variables and cannot be literals or expressions.
Valid Invalid Invalid

def add(a,b): def add(a+1,b): def add(5,’b’):


print(a+b) print(a+b) print(a+b)

a,b are variables, Here a+1 is an expression, Here 5,’b’ are literals,
Hence valid fn definition. Hence invalid fn definition. hence invalid fn definition.
HOW FUNCTIONS RETURN A VALUE
• Syntax:
def function_name(arguments):
return <value>
• Return statement: returns the value of the expression following return keyword.
• *It is used to end the execution of function call and specifies what value is to be returned back to calling
function.
• Function can take input values as parameters, execute them and return output to the calling function with a
return statement.
• Example:
def areaRectangle(length, breadth): Output
area= length * breadth 600
return area
Result= areaRectangle(30, 20)
print(Result)
HOW FUNCTIONS RETURN A VALUE CONTINUED…..
• If the return statement is absent and when we call a function, the default value None is
returned.
• Example:
def add(a,b): def add(a,b):
s=a+b s=a+b
result=add(10,20) return s
print(result) result=add(10,20)
print(result)
Output is None Output is 30
HOW FUNCTIONS RETURN MULTIPLE VALUES
• A function in Python can return multiple values.
• A return statement can return any number of values and the calling function receive the values in one of
the following ways:
1. By specifying same number of variables on the left-hand side of assignment operator in a
function call.
Example:
def calc( a,b):
add= a+b
sub= a-b
mul= a*b
return add, sub, mul
x, y,z= calc(200,180) Output
print(x, y,z) 380 20 36000
HOW FUNCTIONS RETURN A VALUE
2. By receiving the returned values in the form of a tuple.
• Example:
def calc( a,b):
add= a+b
sub= a-b
mul= a*b
return add, sub, mul
result= calc(200,180) Output
print(result) (380, 20, 36000)
TYPES OF USER-DEFINED FUNCTIONS

Functions with no arguments and no


return value.

Functions with arguments but no


return value.

Functions with arguments and return


value.

Functions with no arguments but


return value.
FUNCTIONS WITH NO ARGUMENTS AND NO RETURN VALUES
• These types of functions do not take any value or argument and do not return any value.
• Example:`
def add():
n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
s=n1+n2
print(s)
add()
FUNCTIONS WITH ARGUMENTS BUT NO RETURN VALUE
• Here, parameters are given in the parentheses separated by comma.
• Values are passed for the parameters at the function calling.
• Example:
def add(a,b):
s=a+b
print(s)
n1=int(input(“Enter First Number:”))
n2=int(input(“Enter Second Number:”))
add(n1,n2)
FUNCTIONS WITH ARGUMENTS & RETURN VALUE
• This involves both parameter passing with a returned value.
• We can return values using return statement.
• Example:
def add(a,b):
s=a+b
return s
n1=int(input("enter First Number:"))
n2=int(input("Enter Second Number:"))
print(add(n1,n2))
FUNCTIONS WITH NO ARGUMENTS BUT RETURN VALUE
• Here, the function may not take any arguments but returns a value to the calling
function.
• Example:
def add():
a=int(input("enter First Number:"))
b=int(input("Enter Second Number:"))
s=a+b
return s
print(add())
ACTIVITY
1. Write a program to generate the multiplication table for an inputted number
using user defined function table by passing the number as the parameter.
2. Write a user defined function square(n), where ‘n’ is the number whose square
is to be calculated. The function should return the square of the given number .
3. Write a user defined function fact() which takes an integer value as an
argument and return the factorial of the given integer.
4. Write a python program to print the even numbers in the given list by passing
list as a parameter to the function.
5. Write a menu driven program to implement calculator functions using user
defined functions.
ACTIVITY
1. Find the output for the following:
def Show(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
elif i%2==0:
m=m+str[i-1]
else:
m=m+"#"
print(m)
Show('Happy Birthday')
ACTIVITY
2.Find the output for the following code:
Text="Welcome Python"
L=len(Text)
m=""
for i in range (0,L):
if Text[i].isupper():
m=m+Text[i].lower()
elif Text[i].isalpha():
m=m+Text[i].upper()
else:
m=m+"!!"
print (m)
LET’S RECAP…
• User-defined Functions
• How Parameters and arguments are passed to the functions.
• Types of user-defined functions

You might also like