User Defined Functions

Chapter 7 • Python
Chapter 7 • Python

User Defined Functions

पायथन में खुद के function बनाना सीखें। Define करना, call करना, arguments, function के types और recursion — सब कुछ यहाँ है! Date: 18/12/21

Define & Invoke
All Argument Types
4 Function Types
Recursion

Introduction →

पायथन में built-in library function के अलावा user स्वयं function बना सकता है। यूजर के द्वारा बनाए गए function user defined function कहलाते हैं।

एक बार function बनाने के बाद उसे बार-बार call करके प्रयोग किया जा सकता है।

📝 फंक्शन बनाने तथा प्रयोग करने के लिए दो स्टेप्स हैं:
1. Define a function
2. Calling to function or Invoking a function

1. Define a function →

def keyword का प्रयोग करके नया function बनाया जाता है तथा उसमें codes लिखे जाते हैं। यह function की definition होती है। function कोई value return कर सकता है या नहीं भी।

Syntax
python
def <function name> (<list of argument>):
    <statement>
    return <expression>
Example
python
def sum(a, b):
    t = a + b
    return t
💡 def keyword से function शुरू होता है। Function का नाम, parentheses में arguments, और colon (:) लगाना ज़रूरी है। Body indented होती है।

2. Invoking a function →

function define करने के बाद इसके result को प्राप्त करने के लिए function को call किया जाता है। function call करने को invoking कहा जाता है।

function के नाम invoking का प्रयोग करके call किया जा सकता है।

Syntax
python
<function name> (<list of argument>)
Example
python
def sum(a, b):
    t = a + b
    return t

a = sum(5, 2)
print(a)
print(sum(5 + a))

# Output:
# 7
# 12

Function Argument :-

फंक्शन के अंदर में प्रयोग किये गये variables function argument कहलाते हैं।

ये calling function से आने वाली value को प्राप्त करते हैं तथा store करते हैं।

📝 पायथन तीन प्रकार के argument support करता है — (i) Positional argument  (ii) Default argument  (iii) Named argument
(i) Positional argumentarguments की संख्या values के समान होनी चाहिए

जिन arguments की संख्या arguments के समान मानों की आवश्यकता होती है positional argument कहलाते हैं।

python
def sum(a, b):
    t = a + b
    return t

x = y = z = 6
print(sum(5, 6))   # 11
c = sum(x, y)      # 12
d = sum(5, z)      # 11
(ii) Default argumentfunction header में पहले से मान दिए जाते हैं

function header में जिन arguments को पहले से मान दिए जाते हैं वे default argument होते हैं।

python
def sum(a, b=0):
    t = a + b
    return t

x = y = z = 6
print(sum(5, 6))   # → 11
c = sum(x, y)      # → 12
d = sum(5, z)      # → 11
e = sum(9)         # → 9  (b uses default value 0)
(iii) Named / keyword argumentarguments को उनके नाम से pass करना

function calling के समय arguments को उनके नाम से pass करने पर named argument प्रयोग किए जाते हैं। इसमें calling के समय sequence में मान देने की आवश्यकता नहीं होती।

python
def sum(b=4, a=5, c=6):
    t = a + b + c
    return t

z = sum(4, 5, 6)           # positional — 15
x = sum(c=4, a=5, b=3)     # named — 12
y = sum()                  # all defaults — 15
💡 Named arguments में order matter नहीं करता — आप किसी भी क्रम में arguments दे सकते हैं।

Type of Function :-

function argument तथा return value के आधार पर function चार प्रकार के होते हैं —

1Function with Input and Output
2Function with Input, without Output
3Function without Input, with Output
4Function without Input and Output
1

Function with Input and Output :-

इस प्रकार के function एक या अधिक value argument के रूप में input करते हैं तथा एक value return करते हैं।

Program — Factorial

एक program लिखें जिसमें एक number input कर उसके factorial की गणना करें।

python
def fact(a):
    f = 1
    for i in range(a, 0, -1):
        f = f * i
    return f

# main program
n = int(input("Enter any no."))
print(fact(n))
2

Function with Input without Return :-

इस प्रकार के function एक या अधिक argument input करते हैं तथा कोई भी value return नहीं करते।

Program — Table

एक program लिखें जिसमें एक number input कर उसकी table को 10 तक print करें।

python
def table(a):
    for i in range(1, 11):
        print(a, "*", i, "=", a * i)

# main program
n = int(input("Enter any value"))
table(n)
3

Function without Input arg & with Return :-

इस प्रकार के function में input argument नहीं होते परन्तु यह एक value return करते हैं।

Program — Even Sum (First 50)

पहले 50 सम संख्याओं की गणना कर print करने के लिए एक program लिखें।

python
def even_sum():
    t = 0
    for a in range(1, 51):
        t = t + a * 2
    return t

print(even_sum())
4

Function without Input & Output :-

इस प्रकार के function ना तो कोई argument input करते हैं और ना ही कोई value return करते हैं।

Program — Pattern

निम्न pattern उत्पन्न करने के लिए एक program लिखें।

python
def pattern():
    for a in range(1, 6):
        for b in range(a, 5):
            print(" ", end=" ")
        for c in range(1, a + 1):
            print(c, end=" ")
        print(" ")

# main program
pattern()

# Output Pattern:
#         1
#       1 2
#     1 2 3
#   1 2 3 4
# 1 2 3 4 5

Recursion —

जब एक function स्वयं को call करता है तब यह प्रक्रिया recursion कहलाती है।

Recursion एक loop के समान कार्य करता है जिसे रोकने के लिए एक terminate condition दी जाती है।

Direct Recursion (खुद को call करना)

python
def test():
    test()

Indirect Recursion (दूसरे function के through)

python
def test():
    retest()

def retest():
    test()
⚠️ Recursion में हमेशा एक base condition (terminate condition) होनी चाहिए। बिना इसके program infinite loop में चला जाएगा।
Program — Sum of N Natural Numbers (Recursion)

पहले N प्राकृतिक संख्याओं का योग print करने के लिए recursion program बनाएं।

python
def sum(a):
    if a == 1:
        return 1
    else:
        return a + sum(a - 1)

# main program
n = int(input("Enter any value"))
print(sum(n))

# Example: n = 5
# sum(5) = 5 + sum(4)
# sum(4) = 4 + sum(3)
# sum(3) = 3 + sum(2)
# sum(2) = 2 + sum(1)
# sum(1) = 1  ← base case
# Result = 5 + 4 + 3 + 2 + 1 = 15

Recursion के Key Points :

  • एक function जो खुद को call करे वह recursive function है
  • Base condition अनिवार्य है — वरना Stack Overflow!
  • हर recursive call problem को छोटा बनाती जाती है
  • Python का default recursion limit = 1000

Practice Questions :-

इन programs को खुद लिखने का प्रयास करें — Chapter 7 को और अच्छे से समझने के लिए 💪

Q1
Write a function to find the sum of two numbers and return the result.
Q2
Write a function that takes a number and prints its multiplication table up to 10.
Q3
Write a function (no input, no return) to print a right-angle triangle pattern of stars.
Q4
Write a recursive function to find the factorial of a number.
Q5
Write a function to check whether a given number is even or odd.
Q6
Write a function to find the largest of three numbers using arguments.
Q7
Write a function using default argument to calculate simple interest (default rate = 5%).
Q8
Write a function using keyword arguments to display student details (name, roll, marks).
Q9
Write a recursive function to calculate the sum of first N natural numbers.
Q10
Write a function (no input, with return) to return the sum of first 100 natural numbers.
Q11
Write a function to count and return the number of vowels in a given string.
Q12
Write a function to reverse a string and return the reversed string.
Q13
Write a recursive function to calculate power (x^n) without using the ** operator.
Q14
Write a function to check whether a number is prime and return True/False.
Q15
Write a function using positional arguments to calculate the area of a rectangle.
Hi! 👋
KnoblyAI
Online

Hello! 👋

Your futuristic AI learning companion

KnoblyAI can make mistakes. Double-check important replies.