Python

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Python

USER-DEFINED
FUNCTIONS
BY:- Madhulika Wakalkar
ROLL NO. 19
What is User-defined
function?
A user-defined function in Python is a custom function created by the
programmer to perform a specific task. It allows you to encapsulate a
block of code that you can reuse throughout your program.

We can modify a user-defined function as per our requirements. Thus, a


user-defined function helps us create definitions that are not a part of
the in-built Python functions. It can help to cater to our needs.
Function definition
In Python, defining the function works as follows. def is the
keyword for defining a function. The function name is
followed by parameter(s) in (). The colon : signals the start
of the function body, which is marked by indentation. Inside
the function body, the return statement determines the
value to be returned. After function definition is complete,
calling the function with an argument returns a value.
Syntax:-
def function_name(argument1, argument2, ...) :
statement_1 statement_2
function calling
Calling a function in Python is similar to other programming languages,
using the function name, parenthesis (opening and closing) and
parameter(s). we can call it by using the name of the function followed by
parenthesis containing parameters of that particular function.
Syntax:-
function_name(arg1, arg2)

EG:- def avg_number(x, y):


print("Average of ",x," and ",y, " is ",(x+y)/2))
avg_number(3, 4)
Output: Average of 3 and 4 is 3.5

here, in line 3, we are calling the function [ avg_number(3,4) ]


function arguments and
parameter passing
Information can be passed into functions as arguments. Arguments are
the values passed inside the parenthesis of the function. Arguments
are specified after the function name, inside the parentheses. A
function can have any number of arguments separated by a comma.
eg-
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
evenOdd(2)
return statement
A return statement is used to end the execution of the function call and
“returns” the result to the caller.

The statements after the return statements are not executed.

The return statement can consist of a variable, an expression, or a


constant which is returned at the end of the function execution. If none
of the above is present with the return statement a None object is
returned.

syntax:-
return [expression_list]
Thank you

You might also like