Ravindra BagaleCourses & study guides मराठी Track your progress

Python Functions Tutorial: def, return, Arguments and lambda with Examples

P7.1 What Is a Function in Python and Why Use It

Why. If a GST or VAT rule changes, you want to fix it in one place, not in 20 cells. A function holds the rule once.

What. A function is a named block of code. You define it once with def and call it many times. You already used built-in functions: print, len, sum, round.

How.

Define and call a function

  1. Write def, a name, brackets and a colon.
  2. Indent the body.
  3. Call it by its name with brackets.
1. You call add_vat(100)2. 100 goes into the parameter3. The body runs4. return sends back the answer5. The answer appears where you called it
Calling a function (read from top to bottom)

Worked example A — The smallest function.

Step 1 — What we do. A function that prints a greeting for a support team.

Step 2 — Type and run this code.

def greet():
    print("Hello, how can we help?")

greet()
greet()

Step 3 — Output you should see.

Hello, how can we help?
Hello, how can we help?

Step 4 — What it means. Defined once, called twice. Defining alone does nothing — you must call it.

Worked example B — A function with an input.

Step 1 — What we do. We greet a customer by name.

Step 2 — Type and run this code.

def greet(name):
    print(f"Hello {name}, how can we help?")

greet("Aisha")
greet("Marco")

Step 3 — Output you should see.

Hello Aisha, how can we help?
Hello Marco, how can we help?

Step 4 — What it means. name is a parameter: a placeholder filled by each call.

Ravindra Bagale's Tip

Give functions verb names: calculate_tax, clean_city, load_orders. A function does something.