Important Notice:

**kwargs

**kwargs

18 views 1 min read

**kwargs :-

 Python में **kwargs का उपयोग किसी function में arbitrary number of keyword arguments प्राप्त करने के लिए किया जाता है। ये arguments function के अंदर एक dictionary के रूप में उपलब्ध होते हैं।

English Definition: **kwargs allows a function to accept any number of keyword arguments. These arguments are collected into a dictionary.

Syntax:

def function_name(**kwargs):
    # statements
    pass

Example 1: Display Keyword Arguments

def display(**kwargs):
    print(kwargs)

display(name="Rahul", age=18, city="Azamgarh")

Output:

{'name': 'Rahul', 'age': 18, 'city': 'Azamgarh'}

Explanation:

  • name, age और city keyword argument names हैं।

  • उनके corresponding values dictionary में store होती हैं।

  • kwargs एक dictionary है, जिसमें keys और values होती हैं।

 

Example 2: Display Student Details

def student_details(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)

student_details(name="Amit", course="O Level", marks=85)

Output:

name : Amit
course : O Level
marks : 85
 
यहाँ result dictionary के रूप में इसलिए नहीं आया क्योंकि आपने kwargs को सीधे print() नहीं किया, बल्कि for loop की मदद से dictionary की प्रत्येक key और value को अलग-अलग print किया है।
 

Example 3: Access a Particular Value

def student(**kwargs):
    print("Name:", kwargs["name"])
    print("Marks:", kwargs["marks"])

student(name="Neha", marks=90)

Output:

Name: Neha
Marks: 90

Important: यदि dictionary में कोई key मौजूद नहीं है और उसे kwargs["key"] से access किया जाता है, तो KeyError आ सकता है। Optional key के लिए kwargs.get("key") इस्तेमाल कर सकते हैं।

Related Notes