What is a function?#
A function is a named block of code that performs a task. You write it once and call (use) it as many times as you want.
You have already used built-in functions: print(), len(), input(), max(). Now you'll create your own.
Why functions?
- Reuse - write once, use everywhere.
- Organisation - break a big program into small, named pieces.
- Easier testing & fixing - a bug is fixed in one place.
Function एक मशीन की तरह है: आप उसमें कुछ डालते हैं (input / parameters), वह अंदर कुछ काम करती है, और आपको नतीजा (output / return value) देती है।
जैसे जूस मशीन - संतरे डालो, जूस निकलेगा। आपको हर बार यह नहीं सोचना पड़ता कि मशीन अंदर कैसे काम करती है; बस उसका नाम लेकर (call करके) इस्तेमाल करो।
एक बार function लिख दिया तो उसे 100 जगह इस्तेमाल कर सकते हैं - code बार-बार लिखने की ज़रूरत नहीं।
Defining and calling a function#
def function_name(parameters):
"""Optional description (docstring)."""
# body
return result
Defining a function does not run it. The body runs only when you call it with brackets: greet(). Writing just greet (no brackets) does nothing.
Parameters and arguments#
Parameters are variables listed in the definition. Arguments are the actual values passed in the call.
The number of arguments must match the parameters (unless defaults are used - next lesson):
greet("Riya") # TypeError: greet() missing 1 required positional argument: 'city'
Returning a value#
return sends a result back to the caller. The caller can store it, print it, or use it in a calculation.
return also ends the function immediately. Any code after it (in the same path) doesn't run.
print vs return - a very important difference#
print और return में फर्क - beginners की सबसे बड़ी confusion:
print()सिर्फ screen पर दिखाता है। Function का जवाब आपके program के पास नहीं आता (वहNoneदेता है)।returnजवाब को वापस भेजता है, ताकि आप उसे variable में रख सकें, आगे calculation में इस्तेमाल कर सकें।
उदाहरण: calculator पर answer screen पर दिखना = print; answer को memory (M+) में save करके आगे इस्तेमाल करना = return।
नियम: function के अंदर ज़्यादातर return इस्तेमाल करें, और print बाहर करें।
Returning multiple values#
Return several values separated by commas - Python packs them into a tuple:
Early return#
Docstrings#
A string right after the def line documents what the function does. Tools and help() show it:
Functions calling functions#
Small functions can be combined to build bigger ones:
Function naming tips#
- Use verbs in snake_case:
calculate_total,send_email,is_valid. - A function should do one thing well.
- Functions returning True/False often start with
is_orhas_:is_prime(n).
Summary#
- Define with
def name(params):and call withname(args). - Parameters are names in the definition; arguments are values in the call.
returnsends a value back and ends the function; no return →None.- Prefer returning values over printing inside functions.
- Return multiple values as a tuple; document with docstrings.