Online Computer Courses Classes and Training Program

Python Programming में Function का Tutorial (शुरुआत से सीखने वालों के लिए)

Python Programming में Function का Tutorial


 Python Programming में Function का Tutorial (शुरुआत से सीखने वालों के लिए)

Python में function एक ऐसा block of code होता है, जिसे बार-बार इस्तेमाल किया जा सकता है। Function का उपयोग programming को आसान, modular और organized बनाने के लिए किया जाता है। इस tutorial में हम function को step-by-step समझेंगे।


Function क्या होता है?

Function एक reusable code block है जिसे आप एक बार define करते हैं और बार-बार call कर सकते हैं। इसका उपयोग code repetition को कम करने और readability बढ़ाने के लिए किया जाता है। Python में function दो प्रकार के होते हैं:

  1. Built-in Functions (e.g., print(), len(), etc.)
  2. User-defined Functions (जो आप खुद define करते हैं)

Python में Function कैसे Define करें?

Python में function को define करने के लिए def keyword का उपयोग किया जाता है। Syntax इस प्रकार है:

def function_name(parameters):
    # Function body
    return value

Explanation:

  • def: Function को define करने के लिए इस्तेमाल होता है।
  • function_name: Function का नाम।
  • parameters: Input values जो function को दिए जाते हैं (optional)।
  • return: Output को function से बाहर भेजने के लिए।

एक Simple Function का Example

def greet():
    print("Hello! Welcome to Python Programming.")

इस function को call करने के लिए:

greet()

Output:

Hello! Welcome to Python Programming.

Parameters और Arguments

Function में values pass करने के लिए parameters और arguments का उपयोग होता है।
Example:

def greet_user(name):
    print(f"Hello, {name}! How are you?")

Call Function:

greet_user("Ajay")

Output:

Hello, Ajay! How are you?

Return Statement

जब आप function से कोई value वापस लेना चाहते हैं, तो return keyword का उपयोग किया जाता है।
Example:

def add_numbers(a, b):
    return a + b

Call Function:

result = add_numbers(5, 10)
print("The sum is:", result)

Output:

The sum is: 15

Default Parameters

Function में default value assign करने के लिए default parameters का उपयोग किया जाता है।
Example:

def greet_user(name="Guest"):
    print(f"Hello, {name}!")

Call Function:

greet_user()
greet_user("Ajay")

Output:

Hello, Guest!
Hello, Ajay!

Lambda Functions (Anonymous Functions)

Python में एक special type का function होता है जिसे lambda function कहा जाता है।
Example:

square = lambda x: x ** 2
print(square(4))

Output:

16

Practice Exercise

  1. एक function लिखें जो दो numbers को multiply करे और result return करे।
  2. एक function बनाएं जो list में दिए गए सभी numbers का average calculate करे।

Conclusion:
Python में functions programming को efficient और manageable बनाने के लिए बहुत उपयोगी हैं। इस tutorial में हमने functions की basic understanding को simple तरीके से समझाया है। अब आप अपने programs में functions का उपयोग करना शुरू कर सकते हैं।



नीचे Function से जुड़े कुछ महत्वपूर्ण प्रश्न और उनके उत्तर दिए गए हैं, जो बच्चों को concept को अच्छे से समझने में मदद करेंगे।


Q1: Function क्यों उपयोग किया जाता है?

Ans: Function का उपयोग code को reusable, readable और organized बनाने के लिए किया जाता है। यह code repetition को कम करता है और debugging आसान बनाता है।


Q2: Python में function कैसे define किया जाता है?

Ans: Python में function को def keyword का उपयोग करके define किया जाता है।
Example:

def say_hello():
    print("Hello, World!")

Q3: Python में built-in functions क्या होते हैं? उदाहरण दें।

Ans: Python में कुछ पहले से बने हुए functions होते हैं जिन्हें built-in functions कहते हैं।
Examples:

  1. print() - Output screen पर कुछ दिखाने के लिए।
  2. len() - किसी object की length बताने के लिए।
  3. type() - किसी variable का data type बताने के लिए।

Q4: Parameters और Arguments में क्या अंतर है?

Ans:

  • Parameters: Function define करते समय variables जो आप function में input के रूप में define करते हैं।
  • Arguments: Function call करते समय जो actual values आप parameters को pass करते हैं।

Example:

def add_numbers(a, b):  # a, b are parameters
    return a + b

add_numbers(10, 20)  # 10, 20 are arguments

Q5: Default parameter क्या होता है? उदाहरण दें।

Ans: Default parameter function को call करते समय default value assign करने के लिए उपयोग किया जाता है।
Example:

def greet(name="Guest"):
    print(f"Hello, {name}!")
greet()  # Output: Hello, Guest!
greet("Ajay")  # Output: Hello, Ajay!

Q6: Python में return statement का क्या उपयोग है?

Ans: Return statement function के result को calling point पर वापस भेजने के लिए उपयोग किया जाता है।
Example:

def square(x):
    return x * x
result = square(5)
print(result)  # Output: 25

Q7: Lambda function क्या है? इसका उपयोग कब किया जाता है?

Ans: Lambda function एक छोटा और अनाम (anonymous) function है, जिसे एक लाइन में define किया जाता है। इसका उपयोग छोटे calculations के लिए किया जाता है।
Example:

multiply = lambda x, y: x * y
print(multiply(3, 4))  # Output: 12

Q8: Function को बार-बार call करने का फायदा क्या है?

Ans:

  1. Code reusable बनता है।
  2. Readability और maintainability बढ़ती है।
  3. Errors को fix करना आसान होता है।

Q9: Function में multiple return values कैसे manage करते हैं?

Ans: Python में आप multiple values को tuple के रूप में return कर सकते हैं।
Example:

def calculate(a, b):
    return a + b, a - b
add, sub = calculate(10, 5)
print(add, sub)  # Output: 15 5

Q10: Practice Question

  1. एक function लिखें जो दिए गए list में सबसे बड़ा number return करे।
  2. एक lambda function बनाएं जो दो numbers को divide करे और result return करे।



Python Function - Questions and Answers


Q1: Why are functions used in Python?

Ans: Functions are used to make code reusable, readable, and organized. They reduce code repetition and make debugging easier.


Q2: How do you define a function in Python?

Ans: A function in Python is defined using the def keyword.
Example:

def say_hello():
    print("Hello, World!")

Q3: What are built-in functions? Give examples.

Ans: Built-in functions are pre-defined functions in Python that perform specific tasks.
Examples:

  1. print() - To display output on the screen.
  2. len() - To find the length of an object.
  3. type() - To find the data type of a variable.

Q4: What is the difference between parameters and arguments?

Ans:

  • Parameters: Variables defined in a function definition that accept input values.
  • Arguments: Actual values passed to the function during a function call.

Example:

def add_numbers(a, b):  # a, b are parameters
    return a + b

add_numbers(10, 20)  # 10, 20 are arguments

Q5: What is a default parameter? Give an example.

Ans: A default parameter assigns a default value to a parameter if no argument is provided during the function call.
Example:

def greet(name="Guest"):
    print(f"Hello, {name}!")
greet()  # Output: Hello, Guest!
greet("Ajay")  # Output: Hello, Ajay!

Q6: What is the purpose of the return statement?

Ans: The return statement is used to send a function’s result back to the calling point.
Example:

def square(x):
    return x * x
result = square(5)
print(result)  # Output: 25

Q7: What is a lambda function? When is it used?

Ans: A lambda function is a small, anonymous function defined in a single line. It is used for quick calculations.
Example:

multiply = lambda x, y: x * y
print(multiply(3, 4))  # Output: 12

Q8: What are the benefits of calling a function multiple times?

Ans:

  1. Makes the code reusable.
  2. Improves readability and maintainability.
  3. Simplifies error-fixing.

Q9: How can you manage multiple return values in a function?

Ans: Python allows multiple values to be returned as a tuple.
Example:

def calculate(a, b):
    return a + b, a - b
add, sub = calculate(10, 5)
print(add, sub)  # Output: 15 5

Q10: Practice Questions

  1. Write a function to return the largest number in a given list.
  2. Create a lambda function to divide two numbers and return the result.


Python Functions - Practice Questions with Hindi Explanation


Q1: Create a Function to Find the Largest Number in a List

Problem: Write a function that takes a list of numbers as input and returns the largest number.

Code:

def find_largest(numbers):
    # Use the max() function to find the largest number in the list
    largest = max(numbers)
    return largest

# Test the function
numbers_list = [10, 25, 47, 32, 56, 99]
result = find_largest(numbers_list)
print("The largest number is:", result)

Explanation (Hindi):

  1. Function find_largest() एक list numbers को input के रूप में लेता है।
  2. List में सबसे बड़ा number खोजने के लिए Python के built-in max() function का उपयोग किया गया है।
  3. Function सबसे बड़े number को return करता है।
  4. Test case में list [10, 25, 47, 32, 56, 99] का सबसे बड़ा number 99 है।

Q2: Write a Function to Calculate the Average of Numbers in a List

Problem: Write a function that takes a list of numbers and returns their average.

Code:

def calculate_average(numbers):
    # Calculate the sum of the list and divide by the length of the list
    total = sum(numbers)
    count = len(numbers)
    average = total / count
    return average

# Test the function
numbers_list = [10, 20, 30, 40, 50]
result = calculate_average(numbers_list)
print("The average is:", result)

Explanation (Hindi):

  1. Function calculate_average() एक list numbers को input लेता है।
  2. List के सभी numbers का जोड़ sum() function से किया जाता है।
  3. List में कितने elements हैं, यह len() function से निकाला जाता है।
  4. Average निकालने के लिए total को count से divide किया जाता है।
  5. Function calculated average को return करता है।

Q3: Create a Function to Check if a Number is Even or Odd

Problem: Write a function that takes a number as input and checks if it is even or odd.

Code:

def check_even_odd(number):
    # Use the modulo operator to check divisibility by 2
    if number % 2 == 0:
        return "Even"
    else:
        return "Odd"

# Test the function
num = 15
result = check_even_odd(num)
print(f"The number {num} is {result}.")

Explanation (Hindi):

  1. Function check_even_odd() एक integer number को input लेता है।
  2. Modulo operator % का उपयोग करके यह चेक किया जाता है कि number 2 से divisible है या नहीं।
  3. अगर divisible है, तो function "Even" return करता है; अन्यथा "Odd"।
  4. Function को 15 के साथ test करने पर output "Odd" होगा।

Q4: Write a Function to Reverse a String

Problem: Write a function that takes a string as input and returns the reversed string.

Code:

def reverse_string(text):
    # Use slicing to reverse the string
    reversed_text = text[::-1]
    return reversed_text

# Test the function
input_text = "Python"
result = reverse_string(input_text)
print("The reversed string is:", result)

Explanation (Hindi):

  1. Function reverse_string() एक string text को input के रूप में लेता है।
  2. String को reverse करने के लिए slicing method [::-1] का उपयोग किया गया है।
  3. Function reversed string को return करता है।
  4. Input "Python" के लिए output "nohtyP" होगा।

Q5: Create a Function to Count Vowels in a String

Problem: Write a function that counts the number of vowels in a given string.

Code:

def count_vowels(text):
    # Define a list of vowels
    vowels = "aeiouAEIOU"
    count = 0
    for char in text:
        if char in vowels:
            count += 1
    return count

# Test the function
input_text = "Hello, World!"
result = count_vowels(input_text)
print("The number of vowels is:", result)

Explanation (Hindi):

  1. Function count_vowels() एक string text को input के रूप में लेता है।
  2. Vowels (a, e, i, o, u) की एक list बनाई गई है, जिसमें uppercase और lowercase दोनों शामिल हैं।
  3. String के हर character को loop में चेक किया जाता है कि वह vowel है या नहीं।
  4. अगर vowel मिलता है, तो count को increment किया जाता है।
  5. Function vowels की कुल संख्या को return करता है।

Q6: Write a Function to Generate a Multiplication Table

Problem: Write a function that generates a multiplication table for a given number.

Code:

def multiplication_table(number):
    for i in range(1, 11):
        print(f"{number} x {i} = {number * i}")

# Test the function
multiplication_table(5)

Explanation (Hindi):

  1. Function multiplication_table() एक integer number को input लेता है।
  2. for loop का उपयोग करके 1 से 10 तक iterate किया जाता है।
  3. हर iteration में, number को i से multiply करके table का एक row print किया जाता है।
  4. Input 5 के लिए output:
    5 x 1 = 5
    5 x 2 = 10
    ...
    5 x 10 = 50
    

Practice Exercises:

  1. Write a function to calculate the factorial of a number.
  2. Create a function to check if a string is a palindrome.
  3. Write a function to find the second largest number in a list.



Python Functions - Multiple Choice Questions (MCQs)


Q1: What is the correct way to define a function in Python?

  1. function myFunc():
  2. def myFunc():
  3. define myFunc():
  4. func myFunc():

Answer: 2. def myFunc():


Q2: What does the return statement do in a function?

  1. It stops the function immediately.
  2. It sends the function's result back to the caller.
  3. It prints the result of the function.
  4. It calls another function.

Answer: 2. It sends the function's result back to the caller.


Q3: What is the output of the following code?

def multiply(x, y=2):
    return x * y

print(multiply(5))
  1. 7
  2. 10
  3. Error
  4. None

Answer: 2. 10


Q4: Which of the following is a valid Python function?

  1. def myFunction(): print("Hello")
  2. def myFunction: print("Hello")
  3. myFunction() def: print("Hello")
  4. function myFunction(): print("Hello")

Answer: 1. def myFunction(): print("Hello")


Q5: What will be the output of the following code?

def add_numbers(a, b):
    return a + b

result = add_numbers(3, 5)
print(result)
  1. 35
  2. 8
  3. Error
  4. None

Answer: 2. 8


Q6: Which of the following is NOT true about functions in Python?

  1. Functions can return multiple values.
  2. Functions can have default parameter values.
  3. A function name can start with a number.
  4. Functions can be called multiple times.

Answer: 3. A function name can start with a number.


Q7: What does the following code return?

def divide(a, b):
    return a / b

print(divide(10, 5))
  1. 2.0
  2. 2
  3. Error
  4. None

Answer: 1. 2.0


Q8: What is the output of the following code?

def greet(name):
    print(f"Hello, {name}!")

greet("Ajay")
  1. Hello, name!
  2. Hello, Ajay!
  3. Hello!
  4. Error

Answer: 2. Hello, Ajay!


Q9: Which of the following is an example of a lambda function?

  1. def square(x): return x * x
  2. lambda x: x * x
  3. def lambda x: x * x
  4. lambda: x * x

Answer: 2. lambda x: x * x


Q10: What is the output of the following code?

def check_even_odd(num):
    return "Even" if num % 2 == 0 else "Odd"

print(check_even_odd(9))
  1. Even
  2. Odd
  3. Error
  4. None

Answer: 2. Odd


Practice MCQs:

  1. Which keyword is used to define a function in Python?
    a. func
    b. function
    c. def
    d. define

  2. What is the output of the following code?

    def square(x):
        return x ** 2
    
    print(square(4))
    

    a. 8
    b. 16
    c. 4
    d. Error


Python Functions - Fill in the Blanks


Fill in the Blanks

  1. The keyword used to define a function in Python is ______.
    Answer: def

  2. A function can have one or more ______ to accept inputs from the user.
    Answer: parameters

  3. The ______ statement is used to send a value back from a function to the caller.
    Answer: return

  4. Default parameter values are defined in the function definition using the ______ operator.
    Answer: =

  5. A ______ function is a function without a name, defined using the lambda keyword.
    Answer: lambda

  6. A function without a return statement returns ______ by default.
    Answer: None

  7. To call a function, use its ______ followed by parentheses ().
    Answer: name

  8. Functions help in reducing code ______ and improving readability.
    Answer: repetition


True/False Questions

  1. A Python function can return multiple values.
    Answer: True

  2. Function names in Python can contain spaces.
    Answer: False

  3. You can call a function without passing the required arguments.
    Answer: False

  4. The return statement can be used multiple times in a single function.
    Answer: True

  5. Lambda functions can have multiple expressions.
    Answer: False

  6. Functions in Python must always return a value.
    Answer: False

  7. Parameters defined in a function are also called arguments.
    Answer: False (Arguments are the values passed, while parameters are the placeholders.)

  8. Functions in Python can be nested inside other functions.
    Answer: True

  9. Python functions cannot modify global variables directly.
    Answer: False

  10. A function can call itself in Python.
    Answer: True






Post a Comment

0 Comments