2/4/26, 7:43 PM Functions
In [9]: '''
Python Functions are a block of statements that does a specific task
A function is a block of code which only runs when it is called.
A function can return data as a result.
A function helps avoiding code repetition.
'''
'''
def: This keyword is used to define a function.
function_name: Choose a descriptive name for your function.
parameters: These are inputs that the function accepts (can be optional).
Function body: This is where you write the code that performs the function's task.
return: This optional statement is used to send a value back from the function.
'''
def fun(): # def is keyword fun is name of the function
print('Hi how r u') #here i am printing the statement inside the function witho
#fun()
def greet():
print('Hello world.! ')
#you can call the function multiple times
greet()
greet()
greet()
greet()
greet()
Hello world.!
Hello world.!
Hello world.!
Hello world.!
Hello world.!
In [4]: def sum():
a=5
b=6
print(a+b)
sum()
11
In [5]: def mult():
a,b=5,6
c=a*b
print(c)
mult()
30
In [23]: '''
A parameter is the variable listed inside the parentheses in the function.
An argument is the actual value that is sent to the function when it is called.
'''
def greet(name):
print('Hello welocme to ',name)
greet('RGUKT')
[Link] 1/3
2/4/26, 7:43 PM Functions
def divide(a,b):# here a, b is a parameter
c=a%b
print(c)
k=divide(21,10) # 21, 10 is argument
Hello welocme to RGUKT
1
In [1]: '''
Imagine you need to identiy given numbers numbers even or odd several times in your
Without functions, you would have to write the same calculation code repeatedly:
'''
def even_odd(x):
if x%2==0:
print('Even')
else:
print('Odd')
x=even_odd(20)
y=even_odd(11)
Even
Odd
In [2]: '''
Return Values
Functions can send data back to the code that called them using the return statemen
When a function reaches a return statement, it stops executing and sends the result
'''
def greet():
return 'Here I am returning the output'
print(greet())
def evenorodd(x):
if x%2==0:
return (x,'Even')
else:
return (x,'Odd')
a=evenorodd(23)
b=evenorodd(11)
c=evenorodd(60)
d=evenorodd(71)
e=evenorodd(90)
f=evenorodd(87)
print(a)
print(b)
print(c)
print(d)
print(e)
print(f)
[Link] 2/3
2/4/26, 7:43 PM Functions
Here I am returning the output
(23, 'Odd')
(11, 'Odd')
(60, 'Even')
(71, 'Odd')
(90, 'Even')
(87, 'Odd')
In [ ]:
[Link] 3/3