Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🔁 Unit 2 – Flow of Control और Functions  ·  Lesson 18

User-defined Functions

Functions क्यों?

Function code का एक नाम वाला block है जो एक ख़ास काम करता है और सिर्फ़ call करने पर चलता है। वही 10 lines पाँच जगह लिखने की बजाय उन्हें एक बार function में लिखकर पाँच बार call करते हैं।

♻️
Reusabilityएक बार लिखो, कई बार use करो।
🧩
Modularityबड़ा program छोटे, साफ़ हिस्सों में (decomposition)।
🐞
आसान debuggingहर function अलग से test और fix।
📖
Readabilitycalculate_gst(price) formula से ज़्यादा आसानी से पढ़ा जाता है।
Functions के फ़ायदे

Functions के प्रकार

🧰
Built-inहमेशा उपलब्ध: print(), input(), len(), max(), int(), round()।
📦
Modules मेंimport चाहिए: math.sqrt(), random.randint(), statistics.mean()।
✍️
User-definedआप def से लिखते हैं।
Python में तीन तरह के functions

Function define और call करना

Syntax
def function_name(parameters):
    """optional docstring"""
    statements
    return value          # optional
Python
def greet():
    print('Good morning!')
    print('Welcome to Class XI')

greet()          # call the function
greet()          # call it again
Good morning! Welcome to Class XI Good morning! Welcome to Class XI

def वाली line function header है; indented lines function body। Function define करने से वह चलता नहीं — greet() से call करने पर चलता है।

Parameters और arguments

Python
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))
Area = 60 Two rooms = 32
area_rectangle(12, 5)arguments (असली values)length = 12, breadth = 5parameters इन्हें लेते हैंreturn 60वापस भेजी value
Arguments क्रम से parameters में copy होते हैं (positional arguments)

Value return करना

return caller को value वापस भेजता है और function को तुरंत ख़त्म कर देता है। बिना return वाला function None वापस देता है।

Python
def show(x):
    print('Value is', x)      # no return statement

result = show(10)
print('Function returned', result)
Value is 10 Function returned None

Print करने वाला function

  • Result screen पर दिखाता है
  • Result आगे use नहीं हो सकता
  • None return करता है

Return करने वाला function

  • Result caller को वापस देता है
  • Store, जोड़, बाद में print कर सकते हैं
  • ज़्यादा useful और reusable
Calculations के लिए return बेहतर

Default और keyword arguments

Python
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
400.0 500.0 1500.0 160.0
  • 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 कर सकते हैं।

Python
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)
Total: 276 Average: 69.0 Highest: 91

Flow of execution

Python file ऊपर से नीचे पढ़ता है। def मिलने पर वह function सिर्फ़ याद रखता है। Function call होने पर control body में कूदता है, उसे चलाता है, और call के बाद वाली line पर लौट आता है।

Python
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)
1. Start 2. Before calling 3. Inside square 4. Back, y = 36
Main programsquare()1. Start, 2. Before callingsquare(6)3. Inside squarereturn 364. Back, y = 36
Control function में जाता है और लौटता है

Mutable और immutable arguments भेजना

Function को भेजी गई list (mutable) बदली जाए तो बदलाव बाहर भी दिखता है। Function के अंदर int या string को re-assign करने से caller पर असर नहीं होता।

Python
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)
[75, 85] 10

Solved programs

True/False return करने वाला function

Python
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)])
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]

एक function दूसरे को call करता है

Python
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))
5! = 120 Ways to choose 3 from 7 = 35

Docstring

Python
def celsius_to_f(c):
    """Convert Celsius to Fahrenheit."""
    return c * 9 / 5 + 32

print(celsius_to_f(37))
print(celsius_to_f.__doc__)
98.6 Convert Celsius to Fahrenheit.

सारांश और practice

  • def name(params): define करता है; name(args) call करता है।
  • return value वापस भेजकर function ख़त्म करता है; return नहीं → None।
  • Default और keyword arguments calls को flexible बनाते हैं।
  • कई values tuple के रूप में return करें।
✅ Practice

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

अक्सर पूछे जाने वाले प्रश्न (FAQ)

Parameter और argument में क्या फ़र्क है?
Parameter function definition में लिखा variable है (def area(l, b))। Argument call करते समय भेजी गई असली value है (area(12, 5))।
return statement न हो तो function क्या return करता है?
अपने आप None return करता है।
क्या default parameters normal parameters से पहले आ सकते हैं?
नहीं। Default value वाले parameters बिना default वालों के बाद आने चाहिए। def f(a, b=2) सही है, def f(a=1, b) SyntaxError है।
← Class 11 Computer Science
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicScope और Modules (math, random) आपकी प्रगति: 18 / 29 (62%) · Lesson 19 / 29 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें