notes 10
notes 10
Example:
def g r e e t ( ) :
message = ” H e l l o , Student ! ” # Local v a r i a b l e
print ( message )
greet ()
# p r i n t ( message ) # This w i l l c a u s e an e r r o r b e c a u s e ’ messa
Global Variable
A global variable is declared outside of all functions. It is accessible from any function
within the program.
Example:
show name ( )
Example:
1
count = 0
def i n c r e m e n t ( ) :
global count
count += 1
print ( ” I n s i d e f u n c t i o n : ” , count )
increment ( )
print ( ” Outside f u n c t i o n : ” , count )
Syntax:
def function_name(parameters):
# code block
return result
Example:
def add ( a , b ) :
return a + b
r e s u l t = add ( 1 0 , 5 )
print ( ”Sum : ” , r e s u l t )
Advantages of Functions
Code Reusability
Modular Programming
Types of Functions
Built-in functions (e.g., len(), print(), range())
2
Local and Global Variables
Local Variable
Local variables are declared within a function and can only be used inside that function.
Example 1:
def s q u a r e ( x ) :
result = x * x # ’ result ’ is a local variable
return r e s u l t
print ( s q u a r e ( 4 ) ) # Output : 16
# print ( result ) # Error : ’ r e s u l t ’ i s not d e f i n e d o u t s i
Example 2: Function with Local and Global Variables
x = 10 # Global v a r i a b l e
def m u l t i p l y ( ) :
y = 5 # Local v a r i a b l e
print ( ” I n s i d e f u n c t i o n : x =” , x )
print ( ” I n s i d e f u n c t i o n : y =” , y )
multiply ()
print ( ” Outside f u n c t i o n : x =” , x )
# p r i n t (” O u t s i d e f u n c t i o n : y =”, y ) # Error : ’ y ’ i s not d e
Global Variable
Global variables are declared outside functions and accessible throughout the program.
Example 3:
count = 100
def a d d t o t o t a l ( v a l u e ) :
global t o t a l
t o t a l += v a l u e
3
Organizing Code Using Functions
Functions help in better structure, modularity, and reusability of code.
User-Defined Function
Example 1:
def g r e e t ( name ) :
print ( ” H e l l o , ” , name )
greet (” Alice ”)
g r e e t ( ”Bob” )
Example 2: Return Multiple Values
def c a l c u l a t e ( a , b ) :
sum = a + b
product = a * b
return sum , product
s , p = c a l c u l a t e (3 , 4)
print ( ”Sum : ” , s )
print ( ” Product : ” , p )
def d i s p l a y a r e a ( r ) :
area = a r e a o f c i r c l e ( r )
print ( ” Area o f c i r c l e : ” , a r e a )
welcome ( ”Kumar” )
welcome ( )
4
Lambda Function (Anonymous)
Example 5:
s q u a r e = lambda x : x * x
print ( s q u a r e ( 6 ) ) # Output : 36
Avoids repetition