User-defined Functions
Functions क्यों?
Function code का एक नाम वाला block है जो एक ख़ास काम करता है और सिर्फ़ call करने पर चलता है। वही 10 lines पाँच जगह लिखने की बजाय उन्हें एक बार function में लिखकर पाँच बार call करते हैं।
Functions के प्रकार
Function define और call करना
def function_name(parameters):
"""optional docstring"""
statements
return value # optionaldef greet():
print('Good morning!')
print('Welcome to Class XI')
greet() # call the function
greet() # call it againdef वाली line function header है; indented lines function body। Function define करने से वह चलता नहीं — greet() से call करने पर चलता है।
Parameters और arguments
def area_rectangle(length, breadth): # parameters
return length * breadth
a = area_rectangle(12, 5) # arguments
print('Area =', a)
print('Two rooms =', area_rectangle(4, 3) + area_rectangle(5, 4))Value return करना
return caller को value वापस भेजता है और function को तुरंत ख़त्म कर देता है। बिना return वाला function None वापस देता है।
def show(x):
print('Value is', x) # no return statement
result = show(10)
print('Function returned', result)Print करने वाला function
- Result screen पर दिखाता है
- Result आगे use नहीं हो सकता
- None return करता है
Return करने वाला function
- Result caller को वापस देता है
- Store, जोड़, बाद में print कर सकते हैं
- ज़्यादा useful और reusable
Default और keyword arguments
def simple_interest(p, r=8, t=1): # r and t have default values
return p * r * t / 100
print(simple_interest(5000)) # r=8, t=1
print(simple_interest(5000, 10)) # t=1
print(simple_interest(5000, 10, 3))
print(simple_interest(t=2, p=1000)) # keyword arguments, any order- Positional arguments position से match होते हैं।
- Default arguments तब use होते हैं जब value न भेजी जाए (
r=8)। - Keyword arguments parameter का नाम लेते हैं (
t=2, p=1000), इसलिए क्रम मायने नहीं रखता।
कई values return करना
Python commas से अलग कई values return कर सकता है; वे tuple के रूप में आती हैं जिसे unpack कर सकते हैं।
def stats(numbers):
total = sum(numbers)
avg = total / len(numbers)
return total, avg, max(numbers) # returns a tuple
t, a, m = stats([45, 78, 62, 91])
print('Total:', t, 'Average:', a, 'Highest:', m)Flow of execution
Python file ऊपर से नीचे पढ़ता है। def मिलने पर वह function सिर्फ़ याद रखता है। Function call होने पर control body में कूदता है, उसे चलाता है, और call के बाद वाली line पर लौट आता है।
print('1. Start')
def square(x):
print('3. Inside square')
return x * x
print('2. Before calling')
y = square(6)
print('4. Back, y =', y)Mutable और immutable arguments भेजना
Function को भेजी गई list (mutable) बदली जाए तो बदलाव बाहर भी दिखता है। Function के अंदर int या string को re-assign करने से caller पर असर नहीं होता।
def add_bonus(marks_list, bonus):
for i in range(len(marks_list)):
marks_list[i] += bonus # list is mutable: caller sees change
def change_number(n):
n = n + 100 # int is immutable: caller does not see change
m = [70, 80]
add_bonus(m, 5)
x = 10
change_number(x)
print(m, x)Solved programs
True/False return करने वाला function
def is_prime(n):
if n < 2:
return False
for d in range(2, int(n ** 0.5) + 1):
if n % d == 0:
return False # return ends the function at once
return True
print([x for x in range(1, 30) if is_prime(x)])एक function दूसरे को call करता है
def factorial(n):
f = 1
for i in range(2, n + 1):
f *= i
return f
def nCr(n, r): # a function calling another function
return factorial(n) // (factorial(r) * factorial(n - r))
print('5! =', factorial(5))
print('Ways to choose 3 from 7 =', nCr(7, 3))Docstring
def celsius_to_f(c):
"""Convert Celsius to Fahrenheit."""
return c * 9 / 5 + 32
print(celsius_to_f(37))
print(celsius_to_f.__doc__)सारांश और practice
def name(params):define करता है;name(args)call करता है।returnvalue वापस भेजकर function ख़त्म करता है; return नहीं → None।- Default और keyword arguments calls को flexible बनाते हैं।
- कई values tuple के रूप में return करें।
Functions लिखें: (1) True/False लौटाने वाला is_even(n), (2) count_vowels(text), (3) power(base, exp=2), (4) दोनों values लौटाने वाला min_max(lst)। Output बताइए: def f(a, b=3): return a * b → print(f(4), f(4, 5), f(b=2, a=7))।
Answer: 12 20 14
