Python Functions का परिचय
In this page:
def function_name():
# body
function_name()
Function क्या है?
Function def keyword से define किया गया एक नाम वाला, reusable code का block है जो सिर्फ़ तभी चलता है जब उसे explicitly call किया जाए -- logic को function में bundle करने का मतलब है इसे एक बार लिखना और code को बार-बार दोहराने के बजाय जितनी बार चाहें invoke करना।
उदाहरण: What is a Function?
def greet(): # defines a reusable function named greet
print("Hello!")
greet() # first call
greet() # second call, runs the same code again
Function को Call करना
def greet(): लिखना सिर्फ़ function की definition को interpreter के साथ register करता है; इसके body के अंदर कुछ भी तब तक execute नहीं होता जब तक आप अलग से इसे call करने के लिए parentheses के साथ greet() न लिखें।
उदाहरण: Calling a Function
def greet():
print("Hi there")
# Nothing runs until greet() is called
greet()
docstrings
docstring एक string literal है जिसे किसी function की body की सबसे पहली line पर रखा जाता है, यह बताते हुए कि function क्या करता है; help() जैसे tools और ज़्यादातर IDEs इसे अपने-आप दिखाते हैं, जिससे यह एक साधारण comment से कहीं ज़्यादा उपयोगी बन जाता है।
उदाहरण: docstrings
def greet():
"""Prints a friendly greeting."""
print("Hello!")
print(greet.__doc__) # __doc__ holds the function's docstring text
Functions में Control Flow
किसी function की body में Python के सभी constructs हो सकते हैं -- conditionals, loops, और अन्य functions की calls -- यानी functions एक line जितने simple हो सकते हैं या अंदर काफ़ी substantial logic को coordinate कर सकते हैं।
उदाहरण: Control Flow in Functions
def classify(n):
if n % 2 == 0:
return "even"
else:
return "odd"
print(classify(4)) # calls the function and prints its return value
Functions का Dynamic Execution
क्योंकि Python में functions first-class objects हैं, आप किसी function को variable में assign कर सकते हैं, कई functions को list में रख सकते हैं, या एक function को दूसरे function के argument के रूप में pass कर सकते हैं -- यानी behavior को खुद एक value की तरह इधर-उधर ले जा सकते हैं, सिर्फ़ data की तरह नहीं।
उदाहरण: Dynamic Execution of Functions
def greet():
print("Hello!")
say_hi = greet # functions are values, so greet can be assigned to another name
say_hi() # calling say_hi runs the same code as greet()
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: