[go: up one dir, main page]

0% found this document useful (0 votes)
2 views36 pages

Functions 2024 25

The document explains the concept of functions in programming, highlighting their definition, usage, and benefits such as modular programming, increased readability, and reusability. It distinguishes between built-in functions and user-defined functions, detailing their syntax and various types, including those with default parameters and variable-length arguments. Additionally, it covers the scope of variables (global vs local), namespaces, and the use of modules in Python for better organization and efficiency in coding.

Uploaded by

thecreepiestbug
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)
2 views36 pages

Functions 2024 25

The document explains the concept of functions in programming, highlighting their definition, usage, and benefits such as modular programming, increased readability, and reusability. It distinguishes between built-in functions and user-defined functions, detailing their syntax and various types, including those with default parameters and variable-length arguments. Additionally, it covers the scope of variables (global vs local), namespaces, and the use of modules in Python for better organization and efficiency in coding.

Uploaded by

thecreepiestbug
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/ 36

Function can be defined as a named group of

instructions that accomplish a specific task when it is


invoked.

Once defined, a function can be called repeatedly


from different places of the program without writing
all the codes of that function every time, or it can be
called from inside another function, by simply
writing the name of the function and passing the
required parameters.

The process of dividing a computer program into


separate independent blocks of code or separate
sub-problems with different names and specific
functionalities is known as Modular Programming.
 Increases readability, particularly for longer code
as by using functions, the program is better
organised and easy to understand.
 Reduces code length as same code is not
required to be written at multiple places in a
program. This also makes debugging easier.
 Increases reusability, as function can be called
from another function or another program. Thus,
we can reuse or build upon already defined
functions and avoid repetitions of writing the
same piece of code.
 Work can be easily divided among team
members and completed in parallel.
Inbuilt Functions :
The Python interpreter has a number of functions
built into it. These are the functions that are
frequently used in a Python program. Such functions
are known as built-in functions. We can directly call
these functions in our program without defining
them. Eg. input(), print() etc.

User Defined Functions:


In addition to the standard library functions, we can
define our own functions while writing the program.
Such functions are called user defined functions.
Thus, a function defined to achieve some task as per
the programmer's requirement is called a user
defined function. Eg. Area(), Series() etc.
A function definition begins with def (short for define). The
syntax for creating a user defined function is as follows:

 Function blocks begin with the keyword def followed by the


function name and parentheses ( ( ) ).
 Any input parameters or arguments should be placed
within these parentheses. You can also define parameters
inside these parentheses.
 The first statement of a function can be an optional
statement - the documentation string of the function or
docstring.
 The code block within every function starts with a colon (:)
and is indented.
 The statement return [expression] exits a function,
optionally passing back an expression to the caller. A return
statement with no arguments is the same as return None.
SYNTAX Function Header

def functionname( [parameter1, parameter2,…]):


"function_docstring"
function_suite Function Block
return [expression]
Write a user defined function to add 2 numbers and display
their sum.
#Function to add two numbers
#The requirements are listed below:
#1. We need to accept 2 numbers from the user.
#2. Calculate their sum
#3. Display the sum.
In the above example, the numbers were accepted from the user
within the function itself, but it is also possible for a user defined
function to receive values at the time of being called. An argument
is a value passed to the function during the function call which is
received in corresponding parameter defined in function header.
#Function to calculate factorial
#The requirements are listed below:
#1. The function should accept one
integer argument from user.
#2. Calculate factorial.
#3. Display factorial
A function may or may not return a value when
called. The return statement returns the values from
the function. In the examples given so far, the
function performs calculations and display
result(s).They do not return any value. Such
functions are called void functions.

But a situation may arise, wherein we need to send


value(s) from the function to its calling function. This
is done using return statement. The return
statement does the following:
• returns the control to the calling function.
• return value(s) or None.
Write a user defined function to add 2 numbers and display
their sum.
#Function to add two numbers
#The requirements are listed below:
#1. We need to accept 2 numbers from the user.
#2. Calculate their sum
#3. Return the sum
#Function to calculate factorial
#The requirements are listed below:
#1. The function should accept one integer argument from user.
#2. Calculate factorial.
#3. Return the factorial
In some programs, user may need to pass string
values as an argument.
Write a user defined function shortname() that
accepts the name as arguments, and display short
name eg. If the name is Aditya Singh Rathore the
function will display ASR.
#Function to calculate Simple Interest

Formal Parameter
The formal arguments
are the
parameters/arguments
Function Definition in a function
declaration.

Actual Parameter
The arguments that
are passed in a
Function Call function call are called
actual arguments
In Python, as per our requirements, we can have the
function in either of the following ways:
 Function with no argument and no return value
 Function with no argument and with return
value(s)
 Function with argument(s) and no return value
 Function with argument(s) and return value(s)
Function with no argument and no return value
Function with no argument and with return value(s)
Function with argument(s) and no return value
Function with argument(s) and return value(s)
Python allows assigning a default value to the
parameter. A default value is a value that is
predecided and assigned to the parameter when the
function call does not have its corresponding
argument.

A default argument is a value provided in a function


declaration that is automatically assigned if the caller
of the function doesn't provide a value for the
argument with a default value.
Rules for Default Parameters :
 The parameters should be in the same order as
that of the arguments.
 The default parameters must be the trailing
parameters in the function header that means if
any parameter is having default value then all the
other parameters to its right must also have
default values.
For example Function Call
1. def calcInt(p, r, t=5) 1. calcInt(p, r, t) or calcInt(p,r)
2. def calcInt(p, r=10, t=5) 2. calcInt(p, r, t) or calcInt(p, r)
3. def calcInt(p=5000, r=10, t=5) or calcInt(p)
3. calcInt(p, r, t) or calcInt(p,r)
Invalid Function Definition or calcInt(p) or calcInt()
def calcInt(p, r=10,t)
def calcInt(p=5000, r=10, t)
def calcInt(p=5000, r, t=5)
These arguments are supplied to a function in the
same order, they are defined in a function definition.
The number and position of argument must be
matched. If we change the order then result will be
affected and if we change the number of arguments
then Type error will occur. Also called required
arguments.
In case we have greater number of arguments to pass
and want to give values only for some specific
variable then to avoid the positional arguments, we
prefer the values to be passed in any order for some
specific variables only, these are called keyword or
named arguments.
Note : Make sure that argument list must have any
positional argument followed by keyword argument.
In case we don’t know the number of values to be
passed to a function, in that case we use variable
length arguments, in such case we may call a function
with different number of arguments passed to it. We
use * preceded to a variable.
Write a program that simulates a traffic light . The program should
consist of the following:
1. A user defined function trafficLight( ) that accepts input from
the user, displays an error message if the user enters anything
other than RED, YELLOW, and GREEN. Function light() is called
and following is displayed depending upon return value from
light().
a) “STOP, your life is precious” if the value returned by light()
is 0.
b) “Please WAIT, till the light is Green “ if the value returned by
light() is 1
c) “GO! Thank you for being patient” if the value returned by
light() is 2.
2. A user defined function light() that accepts a string as input and
returns 0 when the input is RED, 1 when the input is YELLOW
and 2 when the input is GREEN. The input should be passed as
an argument.
3. Display “ SPEED THRILLS BUT KILLS” after the function
trafficLight( ) is executed.
Test code
A variable defined inside a function cannot be accessed outside it.
Every variable has a well-defined accessibility.
The part of the program where a variable is accessible can be defined
as the scope of that variable.
A variable can have one of the following two scopes:
A variable that has global scope is known as a global variable and a
variable that has a local scope is known as a local variable.
(A) Global Variable
In Python, a variable that is defined outside any function or any
block is known as a global variable. It can be accessed in any
functions defined onwards. Any change made to the global
variable will impact all the functions in the program where that
variable can be accessed.
(B) Local Variable
A variable that is defined inside any function or a block is known
as a local variable. It can be accessed only in the function or a
block where it is defined. It exists only till the function executes.
(A)Global Variable
• In Python, a variable that is defined outside any
function or any block is known as a global
variable. It can be accessed in any functions
defined onwards. Any change made to the global
variable will impact all the functions in the
program where that variable can be accessed.
• Global variable is created as execution starts and
is lost when the program ends.
• Parameter passing is not necessary for global
variables.
• A name declared in the top level segment (_main_)
is said to have a global scope and can be used in
entire program.
(B)Local Variable

• A variable that is defined inside any function or a block


is known as a local variable. It can be accessed only in
the function or a block where it is defined. It exists only
till the function executes.
• Local variables are created when the function has
started execution and is lost when the function
terminates.
• Parameter passing is required for local variables.
• The formal parameters also have the local scope
Global Variable

To access any variable outside the function


num = 5
Local Variable
def myFunc1( ):
y = num + 5
print("Accessing num -> (global) in myFunc1, value = ",num)
print("Accessing y-> (local variable of myFunc1) accessible,
value=",y)
# The function myFunc1() ends here

myFunc1()
print("Accessing num outside myFunc1 ",num)
print("Accessing y outside myFunc1 ",y)
NameError: name ‘y’ is not defined .y
generates error when it is accessed outside
myfunc1()
Note:
 Any modification to global variable is permanent and affects all
the functions where it is used.
 If a variable with the same name as the global variable is
defined inside a function, then it is considered local to that
function and hides the global variable.
 If the modified value of a global variable is to be used outside
the function, then the keyword global should be prefixed to the
variable name in the function.
num = 5
def myfunc1():
#Prefixing global informs Python to use the updated global
#variable num outside the function
global num
print("Accessing num =",num)
num = 10
print("num reassigned =",num) Output:
#function ends here Accessing num = 5
num reassigned = 10
myfunc1() Accessing num outside myfunc1 10
print("Accessing num outside myfunc1",num)
Namespaces :
A namespace is a container where names are mapped to
objects, they are used to avoid confusions in cases where
same names exist in different namespaces. They are
created by modules, functions, classes etc.
• Local environment
• Enclosing environment
• Global environment
• Built-in environment
Name Resolution (Resolving Scope of a name)
In Python, the LEGB rule is used to decide the order in which the
namespaces are to be searched for scope resolution.
The scopes are listed below in terms of hierarchy(highest to
lowest/narrowest to broadest):
•Local(L): Defined inside function/class
•Enclosed(E): Defined inside enclosing functions(Nested function
concept)
•Global(G): Defined at the uppermost level
•Built-in(B): Reserved names in Python built in modules.
The Python standard library is an extensive
collection of functions and modules that help the
programmer in the faster development of programs.
While a function is a grouping of instructions, a
module is a grouping of functions.

 A module is a Python file that contains definitions


of multiple functions.
 A module can be imported in a program using
import statement.
 Irrespective of the number of times a module is
imported, it is loaded only once.
 To import specific functions in a program from a
module, from statement can be used.
Module Own.py

import Own

modulename.funcname()
Note:
import statement can be written anywhere in the
program
Module must be imported only once
In order to get a list of modules available in Python,
we can use the following statement:
>>> help("module")

To view the content of a module say math, type the


following:
>>> help("math")

You might also like