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
- Write
def, a name, brackets and a colon. - Indent the body.
- Call it by its name with brackets.
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.
Ravindra Bagale's Tip – मराठी
Functions ला क्रियापदाची नावं द्या: calculate_tax, clean_city, load_orders. Function काहीतरी करतं.
Ravindra Bagale's Tip – हिंदी
Functions को क्रिया वाले नाम दो: calculate_tax, clean_city, load_orders. Function कुछ करता है.