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

User Defined Functions in Python Chapter 2 (1)

Uploaded by

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

User Defined Functions in Python Chapter 2 (1)

Uploaded by

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

Class 12th computer science

USER DEFINED FUNCTIONS IN PYTHON CHAPTER 2

Python Functions is a block of statements that return the specific task. The idea is to put
some commonly or repeatedly done tasks together and make a function so that instead of
writing the same code again and again for different inputs, we can do the function calls to
reuse code contained in it over and over again.

Some Benefits of Using Functions


 Increase Code Readability
 Increase Code Reusability

Python Function Declaration
The syntax to declare a function is:

Types of Functions in Python


Below are the different types of functions in Python:
 Built-in library function: These are Standard functions in Python that are available to
use.
 User-defined function: We can create our own functions based on our requirements.

Er.Deepak Kumar cs faculty sarore


Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of
functionalities and properties to it as we require. By the following example, we can
understand how to write a function in Python. In this way we can create Python function
definition by using def keyword.

# A simple Python function

def fun():

print("Welcome to GFG")

Calling a Function in Python


After creating a function in Python we can call it by using the name of the functions
Python followed by parenthesis containing parameters of that particular function. Below is
the example for calling def function Python.

Python Function Syntax with Parameters

def function_name(parameter: data_type) -> return_type:


"""Docstring"""
# body of the function
return expression

Er.Deepak Kumar cs faculty sarore


Types of Python Function Arguments
Python supports various types of arguments that can be passed at the time of the function
call. In Python, we have the following function argument types in Python:
 Default argument
 Keyword arguments (named arguments)
 Positional arguments
 Arbitrary arguments (variable-length arguments *args and **kwargs

Er.Deepak Kumar cs faculty sarore


Arbitrary Keyword Arguments

In Python Arbitrary Keyword Arguments, *args, and **kwargs can pass a variable number
of arguments to a function using special symbols. There are two special symbols:
 *args in Python (Non-Keyword Arguments)
 **kwargs in Python (Keyword Arguments)
Example 1: Variable length non-keywords argument

Docstring

The first string after the function is called the Document string or Docstring in short. This is
used to describe the functionality of the function. The use of docstring in functions is
optional but it is considered a good practice.
The below syntax can be used to print out the docstring of a function.

Syntax: print(function_name.__doc__)

Er.Deepak Kumar cs faculty sarore


Return Statement in Python Function
The function return statement is used to exit from a function and go back to the function
caller and return the specified value or data item to the caller. The syntax for the return
statement is:

return [expression_list]

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

Er.Deepak Kumar cs faculty sarore


Local and global variables in python
Parameter Local Variables Global Variables

Defined inside a function or Defined outside of all functions or


Definition
block. blocks.

Accessible only within the


Accessible throughout the entire
Scope function/block where it’s
program.
defined.

Exists only during the Remains in memory for the


Lifetime
function’s execution. duration of the program.

Cannot be accessed outside its Can be accessed and modified by


Accessibility
function. any function in the program.

Keyword for Use the global keyword to modify


No special keyword is required.
Modification it inside a function.

Stored in the data segment of


Memory Storage Stored in the stack.
memory.

Risk of Unintended Low, as it’s confined to its Higher, as any function can modify
Modification function. it.

Er.Deepak Kumar cs faculty sarore


FUNCTIONS:

Function is a sub program which consists of set of instructions used to perform a specific
task. A large program is divided into basic building blocks called function.

Need For Function:

when the program is too complex and large they are divided into parts. Each part is
separately coded and combined into single program. Each subprogram is called as function.

Debugging, Testing and maintenance becomes easy when the program is divided into
subprograms.

Functions are used to avoid rewriting same code again and again in a program.

Function provides code re-usability

The length of the program is reduced.

Types of function:

Functions can be classified into two categories:


i) User defined function

ii) Built in function

i) Built in functions

Built in functions are the functions that are already created and stored in python.

These built in functions are always available for usage and accessed by a programmer. It
cannot be modified.

Er.Deepak Kumar cs faculty sarore


ii) User Defined Functions:

User defined functions are the functions that programmers create for their requirement
and use.

These functions can then be combined to form module which can be used in other
programs by importing them.

Advantages of user defined functions:

Programmers working on large project can divide the workload by making


different functions.

If repeated code occurs in a program, function can be used to include those codes
and execute when needed by calling that function.

Er.Deepak Kumar cs faculty sarore


Function definition: (Sub program)

def keyword is used to define a function.

Give the function name after def keyword followed by parentheses in which arguments
are given.

End with colon (:)

Inside the function add the program statements to be executed

End with or without return statement

Syntax:
def fun_name(Parameter1,Parameter2…Parameter n):
statement1
statement2…
statement n
return[expression]

Example:
def my_add(a,b):
c=a+b
return c

Function Calling: (Main Function)

Once we have defined a function, we can call it from another function, program or even
the Python prompt.

To call a function we simply type the function name with appropriate

arguments.
Example:
x=5

Er.Deepak Kumar cs faculty sarore


y=4
my_add(x,y)

Flow of Execution:

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.

Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.

Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the statements
there, and then comes back to pick up where it left off.

Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.

Function Prototypes:

i. Function without arguments and without return type

ii. Function with arguments and without return type

iii. Function without arguments and with return type

iv. Function with arguments and with return type

i) Function without arguments and without return type

Er.Deepak Kumar cs faculty sarore


o In this type no argument is passed through the function call and no output is return to
main function

o The sub function will read the input values perform the operation and print the result
in the same block

ii) Function with arguments and without return type

o Arguments are passed through the function call but output is not return to the main
function

iii) Function without arguments and with return type

o In this type no argument is passed through the function call but output is return to the
main function.

iv) Function with arguments and with return type

In this type arguments are passed through the function call and output is return to the main
function

Without Return Type

Without argument
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
print(c)
add()

Er.Deepak Kumar cs faculty sarore


OUTPUT:
enter a 5
enter b 10
15

With argument
def add(a,b):
c=a+b
print(c)
a=int(input("enter a"))
b=int(input("enter b"))
add(a,b)

OUTPUT:
enter a 5
enter b 10
15

With return type

Without argument
def add():
a=int(input("enter a"))
b=int(input("enter b"))
c=a+b
return c
c=add()
print(c)

Er.Deepak Kumar cs faculty sarore


OUTPUT:
enter a 5
enter b 10
15

With argument
def add(a,b):
c=a+b
return c
a=int(input("enter a"))
b=int(input("enter b"))
c=add(a,b)
print(c)

OUTPUT:
enter a 5
enter b 10
15

Parameters And Arguments:

Parameters:
Parameters are the value(s) provided in the parenthesis when we write function
header.

These are the values required by function to work.

If there is more than one value required, all of them will be listed in parameter
list separated by comma.

Example: def my_add(a,b):

Er.Deepak Kumar cs faculty sarore


Arguments :
Arguments are the value(s) provided in function call/invoke statement.

List of arguments should be supplied in same way as parameters are listed.

Bounding of parameters to arguments is done 1:1, and so there should be same


number and type of arguments as mentioned in parameter list.

Example: my_add(x,y)

RETURN STATEMENT:

The return statement is used to exit a function and go back to the place from
where it was called.

If the return statement has no arguments, then it will not return any values. But
exits from function.

Syntax:
return[expression]

Example:
def my_add(a,b):
c=a+b
return c
x=5
y=4

print(my_add(x,y))

Output:
9

Er.Deepak Kumar cs faculty sarore


ARGUMENTS TYPES:

1. Required Arguments
2. Keyword Arguments
3. Default Arguments
4. Variable length Arguments

1. Required Arguments:
The number of arguments in the function call should match exactly with the function
definition.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details("george",56)
Output:
Name: george
Age 56

2. Keyword Arguments:
Python interpreter is able to use the keywords provided to match the values with
parameters even though if they are arranged in out of order.
def my_details( name, age ):
print("Name: ", name)
print("Age ", age)
return
my_details(age=56,name="george")
Output:
Name: george

Er.Deepak Kumar cs faculty sarore


Age 56

3. Default Arguments:
Assumes a default value if a value is not provided in the function call for that argument.
def my_details( name, age=40 ):
print("Name: ", name)
print("Age ", age)
return
my_details(name="george")
Output:
Name: george
Age 40

4. Variable length Arguments

If we want to specify more arguments than specified while defining the function, variable
length arguments are used. It is denoted by * symbol before parameter.
def my_details(*name ):
print(*name)
my_details("rajan","rahul","micheal",
ärjun")

Output:
rajan rahul micheal ärjun

Er.Deepak Kumar cs faculty sarore

You might also like