0% found this document useful (0 votes)
8 views12 pages

USER DEFINED FUNCTION (1)

Uploaded by

uniquebrain16
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)
8 views12 pages

USER DEFINED FUNCTION (1)

Uploaded by

uniquebrain16
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/ 12

USER DEFINED FUNCTION:

 In all programming and scripting language, a function is a block of


program statements which can be used repetitively in a program.
 It saves the time of a developer.
 User Defined Functions (UDFs) are the functions defined by user to perform
specific task. Like built-in functions, User-Defined Functions also calls same
way.
RULES TO DECLARE UDFS:

FUNCTION
DECLARATION

DEFINITION

FUNCTION CALLING

 In Python, a user-defined function's declaration begins with the keyword


def and followed by the function name.
 The function may take arguments(s) as input within the opening and
closing parentheses, just after the function name followed by a
colon.
 After defining the function name and arguments(s) a block of program
statement(s) start at the next line and these statement(s) must be
indented.
ARGUMENTS AND PARAMETERS:
A parameter is a variable defined by a function which receives a value when
the function is invoked (called).
An argument is a value that is passed to a function when it is invoked.
TYPES OF ARGUMENTS:
1. Default argument
2. Keyword arguments (named arguments)
3. Positional argument
DEFAULT ARGUMENT
In a function, arguments can have default values. We assign default values
to the argument using the ‘=’ (assignment) operator at the time of function
definition. You can define a function with any number of default arguments.
The default value of an argument will be used inside a function if we do not pass a
value to that argument at the time of the function call.
Due to this, the default arguments become optional during the function call.
It overrides the default value if we provide a value to the default
arguments during function calls.
Example 1:
# function with 2 keyword arguments grade and school
def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)
# without passing grade and school
# Passing only the mandatory arguments
student('Jon', 12)
Output:
Student Details: Jon 12 Five ABC School
Example 2:
# function with 2 keyword arguments grade and school
def student(name, age, grade="Five", school="ABC School"):
print('Student Details:', name, age, grade, school)
# not passing a school value (default value is used)
# six is assigned to grade
student('Kelly', 12, 'Six')
# passign all arguments
student('Jessa', 12, 'Seven', 'XYZ School')
Output:
Student Details: Kelly 12 Six ABC School
Student Details: Jessa 12 Seven XYZ School
Note:
def student(name="JON", age=12, grade, school):
ERROR!
Traceback (most recent call last):
File "<main.py>", line 2
def student(name="JON", age=12, grade, school):
^^^^^
Syntax Error: non-default argument follows default argument
KEYWORD ARGUMENT:
Keyword arguments are those arguments where values get assigned to the
arguments by their keyword (name) when the function is called.
It is preceded by the variable name and an (=) assignment operator. The
Keyword Argument is also called a named argument.
EXAMPLE:
# function with 2 keyword arguments
def student(name, age):
print('Student Details:', name, age) OUTPUT:

# default function call Student Details: Jessa 14


student('Jessa', 14)
Student Details: Jon 12
# both keyword arguments
student(name='Jon', age=12) Student Details: Donald 13

# 1 keyword arguments
student('Donald', age=13)
Change the sequence of keyword arguments
You can change the sequence of keyword arguments by using their name in function
calls.
Python allows functions to be called using keyword arguments. But all the keyword
arguments should match the parameters in the function definition.
When we call functions in this way, the order (position) of the arguments can be
changed.
Example:
# both keyword arguments by changing their order
student(age=13, name='Kelly')
Output:
Student Details: Kelly 13

POSITIONAL ARGUMENTS
Positional arguments are those arguments where values get assigned to the
arguments by their position when the function is called.
For example, the 1st positional argument must be 1st when the function is
called. The 2nd positional argument needs to be 2nd when the function is
called, etc.
By default, Python functions are called using the positional arguments.
Example: Program to subtract 2 numbers using positional arguments.
def add(a, b):
print(a - b)
add(a,b) add(a,b)
add(50, 10)
# Output 40

add(10, 50)
# Output -40
add(50,10) add(10,50)
Note: If you try to pass more arguments, you will get an error.
In the positional argument number and position of arguments must be
matched.
If we change the order, then the result may change.
Also, If we change the number of arguments, we will get an error.
def add(a, b):
print(a - b)
add(105, 561, 4)
Output
TypeError: add() takes 2 positional arguments but 3 were given

Important points to remember about function argument


Point 1: Default arguments should follow non-default arguments
Example:
def get_student(name, grade='Five', age):
print(name, age, grade)
# output: SyntaxError: non-default argument follows default argument
Point: Default arguments must follow the default argument in a function
definition
Default arguments must follow the default argument. For example, When you
use the default argument in a definition, all the arguments to their right must
also have default values. Otherwise, you’ll get an error.
Example:
def student(name, grade="Five", age):
print('Student Details:', name, grade, age)
student('Jon', 'Six', 12)
# Output: SyntaxError: non-default argument follows default argument

Point 2: keyword arguments should follow positional arguments only.


we can mix positional arguments with keyword arguments during a function
call. But, a keyword argument must always be after a non-keyword argument
(positional argument). Else, you’ll get an error.
I.e., avoid using keyword argument before positional argument.
Example:
def get_student(name, age, grade):
print(name, age, grade)
get_student(name='Jessa', 12, 'Six')
# Output: SyntaxError: positional argument follows keyword argument
Point 3: The order of keyword arguments is not important, but All the
keyword arguments passed must match one of the arguments accepted by
the function.
Example:
def get_student(name, age, grade):
print(name, age, grade)
get_student(grade='Six', name='Jessa', age=12)
# Output: Jessa 12 Six
get_student(name='Jessa', age=12, standard='Six')
# Output: TypeError: get_student() got an unexpected keyword argument 'standard'
Point 4: No argument should receive a value more than once
def student(name, age, grade):
print('Student Details:', name, grade, age)
student(name='Jon', age=12, grade='Six', age=12)
# Output: SyntaxError: keyword argument repeated
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.
In Python, no need to specify curly braces for the function body. The
only indentation is essential to separate code blocks. Otherwise, you will get an
error.
Syntax of creating a function
def function_name(parameter1, parameter2):
# function body
# write some action
return value
Here,
 function_name: Function name is the name of the function. We can give any
name to function.
 parameter: Parameter is the value passed to the function. We can pass any
number of parameters. Function body uses the parameter’s value to perform
an action
 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.
 A return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword) to
the caller. The statements after the return statements are not executed. If the
return statement is without any expression, then the special value None is
returned. A return statement is overall used to invoke a function so that the
passed statements can be executed.
 Note: Return statement cannot be used outside the function.

Note: While defining a function, we use two keywords, def (mandatory)


and return (optional).

 Creating a function without any parameters without return

 Creating a function with parameters without return

 Creating a function with parameters and return value

 Creating a function without parameters and return value

CREATING A FUNCTION WITHOUT ANY PARAMETERS WITHOUT RETURN

def message():
print("Welcome to PYTHON")
# call function using its name
message()
Output
Welcome to PYTHON

CREATING A FUNCTION WITH PARAMETERS WITHOUT RETURN

# function
def course_func(name, course_name):
print("Hello", name, "Welcome to PYTHON ")
print("Your course name is", course_name)

# call function
course_func('John', 'Python')

Output
Hello John Welcome to PYTHON
Your course name is Python

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
CREATING A FUNCTION WITHOUT PARAMETERS AND RETURN VALUE

def fun():
str = "LEARNING PYTHON"
x = 20
return str, x; # Return tuple, we could also # write (str, x)
str, x = fun() # Assign returned tuple
print(str)
print(x)
Calling a function of a module
You can take advantage of the built-in module and use the functions defined in it.
For example, Python has a random module that is used for generating random
numbers and data. It has various functions to create different types of random data.
Let’s see how to use functions defined in any module.
 First, we need to use the import statement to import a specific function from a
module.
 Next, we can call that function by its name.
# import randint function
from random import randint

# call randint function to get random number


print(randint(10, 20))
# Output 14
1)def add(a,b):
print(a+b)
add(5,8)

2)def add():
a=int(input("a="))
b=int(input("b="))
print(a+b)
add()

3)def add(a,b):
print(a+b)
a=int(input("a="))
b=int(input("b="))
add(a,b)

4) def add(a,b):
return (a+b)
result=add(5,8)
print(result)

You might also like