⚡0 XP🔥0

Functions

Lesson 19 of 33 ⏱ 5 min read ✎ 4 exercises ❓ 5-question quiz ▶ Runs Python

Write reusable blocks of code with def - parameters, arguments, return values, returning multiple values, docstrings and the difference between print and return.

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
▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

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.

▶ Try it YourselfPython
Ctrl + Enter to run

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.

▶ Try it YourselfPython
Ctrl + Enter to run

return also ends the function immediately. Any code after it (in the same path) doesn't run.

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

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:

▶ Try it YourselfPython
Ctrl + Enter to run

Early return#

▶ Try it YourselfPython
Ctrl + Enter to run

Docstrings#

A string right after the def line documents what the function does. Tools and help() show it:

▶ Try it YourselfPython
Ctrl + Enter to run

Functions calling functions#

Small functions can be combined to build bigger ones:

▶ Try it YourselfPython
Ctrl + Enter to run

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_ or has_: is_prime(n).

Summary#

  • Define with def name(params): and call with name(args).
  • Parameters are names in the definition; arguments are values in the call.
  • return sends 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.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Area of a circle

Write a function circle_area(r) that returns the area of a circle (π × r²) using 3.14159 for π, rounded to 2 decimal places.

2

Is even?

Write is_even(n) that returns True if n is even, otherwise False.

3

Grade function

Write get_grade(marks) that returns "A" for 80 and above, "B" for 60-79, "C" for 40-59 and "F" below 40.

4

Statistics

Write stats(numbers) that returns a tuple (minimum, maximum, average) for a list of numbers. Round the average to 1 decimal.

Quick Quiz

Q1.

Which keyword defines a function?

Q2.

What does a function return if it has no return statement?

Q3.

What is printed?

def f(x):
    return x * 2
    print("done")
print(f(4))
Q4.

In def add(a, b):, what are a and b?

Q5.

What is result after result = print("hi")?