0% found this document useful (0 votes)
4 views13 pages

2025 2026 Class XII Computer Science Chapter 2 AW

The document explains the concept of functions in Python, detailing how to define, call, and utilize various types of arguments including required, keyword, default, and variable-length arguments. It also covers the scope of variables, distinguishing between global and local variables, and introduces the LEGB rule for name resolution in Python. Additionally, it provides examples to illustrate the flow of execution and the importance of defining functions before calling them.

Uploaded by

snippyjohn24
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)
4 views13 pages

2025 2026 Class XII Computer Science Chapter 2 AW

The document explains the concept of functions in Python, detailing how to define, call, and utilize various types of arguments including required, keyword, default, and variable-length arguments. It also covers the scope of variables, distinguishing between global and local variables, and introduces the LEGB rule for name resolution in Python. Additionally, it provides examples to illustrate the flow of execution and the importance of defining functions before calling them.

Uploaded by

snippyjohn24
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/ 13

A function is a block of organized, reusable code that is used to perform a

single, related action. Functions provide better modularity for your


application and a high degree of code reusing.
As you already know, Python gives you many built-in functions like print, etc.
but you can also create your own functions. These functions are called user-
defined functions.
Defining a Function
You can define functions to provide the required functionality. Here are simple
rules to define a function in Python.
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
def functionname( [parameters]):
"function_docstring"
function_body
[ return [expression]]
By default, parameters have a positional behavior and you need to inform them
in the same order that they were defined.
Example
The following function takes a string as input parameter and prints it on
standard screen.
def printme( str ):
"This prints a passed string into this function"
Print(str)
Calling a Function
Defining a function only gives it a name, specifies the parameters that are to
be included in the function and structures the blocks of code.
Once the basic structure of a function is finalized, you can execute it by
calling it from another function or directly from the Python prompt.
Following is the example to call printme function −

# Now you can call printme function


printme("I'm first call to user definedfunction!")
printme("Again second call to the same function")
Function Arguments
You can call a function by using the following types of formal arguments:
• Required arguments
• Keyword arguments
• Default arguments

• Variable-length arguments

Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call should
match exactly with the function definition.
To call the function printme, you definitely need to pass one argument,
otherwise it gives a syntax error as follows –
def printme( str ):
"This prints a passed string into this function"
print( str)
# Now you can call printme function
printme()
When the above code is executed, it produces the following result:
Traceback (most recent call last): File "test.py", line 11, in <module>
printme();
TypeError: printme() takes exactly 1 argument (0 given)
Keyword arguments (Not in syllabus)
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the arguments
by the parameter name.
This allows you to skip arguments or place them out of order because the
Python interpreter is able to use the keywords provided to match the values with
parameters. You can also make keyword calls to the printme function in the
following ways –
# Function definition is here
def printme( str ):
#"This prints a passed string into this function"
print( str)
# Now you can call printme function
printme( str = "My string")
The following example gives more clear picture. Note that the order of
parameters does not matter.
def printinfo( name, age ):
print ("Name: ", name)
print ("Age ", age )
printinfo( age=50, name="miki" )
Default arguments
A default argument is an argument that assumes a default value if a value is not
provided in the function call for that argument. The following example gives
an idea on default arguments, it prints default age if it is not passed –
def printinfo( name, age = 35 ):
print("Name",name);
print( "Age ", age)
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Note : default arguments should follow non-default arguments. Failing to do so
results in syntax error as shown in the example below :
def multiplication(num1=2,num2):
return (num1*num2)

SyntaxError: non-default argument follows default argument


Mixing Positional and Keyword Arguments
It is possible to mix positional arguments and Keyword arguments, but for this positional
argument must appear before any Keyword arguments. Let's see this through an example.
def my_func(a, b, c):
print(a, b, c)
# using positional arguments only
my_func(12, 13, 14)

# here first argument is passed as positional arguments while other two as keyword argum
ent
my_func(12, b=13, c=14)

# same as above
my_func(12, c=13, b=14)

# this is wrong as positional argument must appear before any keyword argument
# my_func(12, b=13, 14)

Illustrating the working of functions


def fun(a,b=1,c=5):
print(a,b,c)

fun(3) # function 1
fun(3,7,10) # function2
fun(25,c=20) # function 3
fun(c=20,a=10) # function 4
#fun(29,b=10,20) # function 5 error positional argument follows keyword argument
#fun(37,a=47) # function 6 error multiple values assign for a
# fun(d=56) # function 7 error unexpected keyword argument d
fun(b=56) # function 8 error required argument to a is missing correction fun(56) or
fun(a=56)

'''correction for function 5


fun(29,b=10,c=20)
correction for function 6
fun(37)
fun(a=47)

correcttion for function 7


fun(56)
fun(b=56)

'''

Variable-length arguments (Not in syllabus)


If you do not know how many arguments that will be passed into your function, add
a * before the parameter name in the function definition.

This way the function will receive a tuple of arguments, and can access the items
accordingly:
# example 1 of variable length arguments
def add(*N):
for I in N:
print(I,end=' ')
print()
add(10,20,30,40)
add(2,4)
add()
# example 2 of variable length arguments
def my_function(*kids):
print("The youngest child is " + kids[2])

my_function("Emil", "Tobias", "Linus")

The return Statement


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.
All the above examples are not returning any value. You can return a value
from a function as follows –
def Add( arg1, arg2 ):
total = arg1 + arg2
print ("Inside the function : ", total_
return total;

total = sum( 10, 20 );


print ("Outside the function : ", total)
Returning multiple values from Function

We can return multiple values from function using the return statement by separating them
with a comma (,). Multiple values are returned as tuples.
def bigger(a, b):
if a > b:
return a, b
else:
return b, a

s = bigger(12, 100)
print(s)
print(type(s))

Expected Output:
(100, 12)
<class 'tuple'>

Scope of Variables
All variables in a program may not be accessible at all locations in that
program. This depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can
access a particular identifier. There are two basic scopes of variables in
Python −
Global variables Local variables

Global vs. Local variables


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.
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.
Variables that are defined inside a function body have a local scope, and
those defined outside have a global scope.
This means that local variables can be accessed only inside the function in
which they are declared, whereas global variables can be accessed
throughout the program body by all functions. When you call a function, the
variables declared inside it are brought into scope.
Following is a simple example −

total = 0 # This is global variable. # Function definition is here


def sum( arg1, arg2 ):
# Add both the parameters and return them."
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total)
return total;

# Now you can call sum function


sum( 10, 20 );
print ("Outside the function global total : ", total)
When the above code is executed, it produces the following result −
Inside the function local total : 30
Outside the function global total : 0

Example 1:
global_var = 12 # a global variable

def func():
local_var = 100 # this is local variable
print(global_var) # you can access global variables in side function

func() # calling function func()

#print(local_var) # you can't access local_var outside the function, because as soon as
function ends local_var is destroyed
Example 2:
xy = 100

def cool():
xy = 200 # xy inside the function is totally different from xy outside the function
print(xy) # this will print local xy variable i.e 200

cool()

print(xy) # this will print global xy variable i.e 100

You can bind local variable in the global scope by using the global keyword followed by
the names of variables separated by comma (,).
Example 3:
t=1

def increment():
global t # now t inside the function is same as t outside the function
t=t+1
print(t) # Displays 2

increment()
print(t) # Displays 2

Note that you can't assign a value to variable while declaring them global .

Example 4:

t=1

def increment():
#global t = 1 # this is error
global t
t = 100 # this is okay
t=t+1
print(t) # Displays 101

increment()
print(t) # Displays 101

Note: In fact there is no need to declare global variables outside the function. You can
declare them global inside the function.

Example 5:

def foo():
global x # x is declared as global so it is available outside the function
x = 100

foo()
print(x)

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
Flow of Execution :
Flow of execution can be defined as the order in which the statements in a program are
executed. The Python interpreter starts executing the instructions in a program from the
first statement. The statements are executed one by one, in the order of appearance from
top to bottom. When the interpreter encounters a function definition, the statements inside
the function are not executed until the function is called. Later, when the interpreter
encounters a function call, there is a little deviation in the flow of execution. In that case,
instead of going to the next statement, the control jumps to the called function and executes
the statement of that function. After that, the control comes back the point of function call
so that the remaining statements in the program can be executed. Therefore, when we read
a program, we should not simply read from top to bottom. Instead, we should follow the
flow of control or execution. It is also important to note that a function must be defined
before its call within a program.
Example 1:
def Greetings(Name):
print("Hello "+Name)
Greetings("John")
print("Thanks")

Example 2:
def RectangleArea(l,b):
return l*b
l = input("Length: ")
b = input("Breadth: ")
Area = RectangleArea(l,b)
print(Area)
print("thanks")
Example 3:
helloPython() #Function Call
def helloPython(): #Function definition
print("I love Programming")

On executing the above code Example 3, the following error is produced:


Traceback (most recent call last):
File "C:\Users\\Prog 7-11.py", line 3, in <module>
helloPython() #Function Call
NameError: name 'helloPython' is not defined

The error ‘function not defined’ is produced even though the function has been defined.
When a function call is encountered, the control has to jump to the function definition and
execute it. In the above program, since the function call precedes the function definition,
the interpreter does not find the function definition and hence an error is raised.

That is why, the function definition should be made before the function call as shown
below:
def helloPython(): #Function definition
print("I love Programming")
helloPython() #Function Call

LEGB Rule for Python Scope


The LEGB stands for Local, Enclosing, Global and Built-in.
Python resolves names using the LEGB rules.
The LEGB rule is a kind of name lookup procedure, which determines the order in which
Python looks up names.
For example, if we access a name, then Python will look that name up sequentially in the
local, enclosing, global, and built-in scope.
Local (or function) scope
It is the code block or body of any Python function or lambda expression. This Python
scope contains the names that you define inside the function. These names will only be
visible from the code of the function. It’s created at function call, not at function definition,
so we have as many different local scopes as function calls. It is applicable if we call the
same function multiple times, or recursively. Each call will result in a new local scope
being created.
Enclosing (or nonlocal) scope
It is a special scope that only exists for nested functions. If the local scope is an inner or
nested function, then the enclosing scope is the scope of the outer or enclosing function.
This scope contains the names that you define in the enclosing function. The names in the
enclosing scope are visible from the code of the inner and enclosing functions.
Global (or module) scope
It is the top-most scope in a Python program, script, or module. This scope contains all of
the names that are defined at the top level of a program or a module. Names in this Python
scope are visible from everywhere in your code.
Built-in scope
It is a special scope which is created or loaded at script run or opens an interactive session.
This scope contains names such as keywords, functions, exceptions, and other attributes
that are built into Python.
Names in this scope are also available from everywhere in your code.
Example
#var1 is in the global namespace
var1 = 5
def ABC( ):
# var2 is in the local namespace
var2 = 6
def XYZ( ):
# var3 is in the nested local
# namespace
var3 = 7
In this example, the var1 is declared in the global namespace because it is not enclosed
inside any function. So it is accessible everywhere in the script.
var2 is inside the ABC( ). So, it can be accessed only inside the ABC( ) and outside the
function, it no longer exists.
var3 also has a local scope, the function is nested and we can use var3 only inside XYZ( ).

5.

You might also like