Function in Python: A Complete Guide to def, Arguments, return, and Scope

A function in Python is a reusable, named block of code that performs a single job. You define it once, give it a name, and then run it as many times as you need by calling that name. Functions are the building blocks of every real Python program, from a two-line script to a system spanning thousands of files.

If you have ever copied and pasted the same five lines of code in three places and then had to fix a bug in all three, you already understand why functions exist. Instead of repeating logic, you wrap it in a function, name it, and call it. This guide walks through everything you need: defining a function with `def`, parameters versus arguments, return values, default and keyword arguments, `*args` and `**kwargs`, variable scope, docstrings, and lambdas, with runnable code and output at every step.

Key Takeaways
• A function in Python is a named, reusable block of code defined with the `def` keyword.
Parameters are the names in the definition; arguments are the actual values you pass when calling.
• `return` sends a value back to the caller. A function with no `return` gives back `None`.
Default parameters (`def f(x, y=10)`) let arguments be optional; keyword arguments let you pass values by name.
• Variables created inside a function are local: what happens inside the function stays inside unless you `return` it.
• The deep value of functions is not reuse alone. It is naming and containing complexity so you can reason about your program one piece at a time.

What is a function in Python?

A function is a chunk of code that you have given a name. Once named, you can run that chunk by writing its name followed by parentheses. Python ships with many built-in functions you have already used, such as `print()`, `len()`, and `type()`.

“`python print(len(“hello”)) # len() is a built-in function

“`

The real power comes when you write your own functions. That is what the rest of this guide covers. If you are brand new to the language, the guide is a good companion before you go deeper here.

How do you define a function with def?

You define a function using the `def` keyword, followed by the function name, parentheses, and a colon. The indented lines below it form the function body.

“`python def greet(): print(“Hello, developer!”) “`

That code defines the function but does not run it yet. Defining a function and calling a function are two separate steps.

How do you call a function?

To call (or invoke) a function, write its name followed by parentheses:

“`python def greet(): print(“Hello, developer!”)

greet() greet()

“`

Calling `greet()` twice runs the body twice. The function was defined once but reused as often as needed.

What is the difference between parameters and arguments?

A parameter is a variable named in the function definition. An argument is the actual value you pass in when you call the function. People often use the words interchangeably, but the distinction is useful.

“`python def greet(name): # ‘name’ is a parameter print(f”Hello, {name}!”)

greet(“Ravi”) # “Ravi” is an argument greet(“Aisha”) # “Aisha” is an argument

“`

A function can take multiple parameters, separated by commas:

“`python def add(a, b): print(a + b)

add(3, 4)

“`

For a deeper look at all the ways to pass values, see .

What does return do in a function?

The `return` statement sends a value back to wherever the function was called. This is different from `print()`, which only displays text on screen. A returned value can be stored in a variable and used later.

“`python def add(a, b): return a + b

result = add(3, 4) print(result) print(add(10, 5) * 2)

“`

Notice that `add` does not print anything itself. It hands the value back, and the caller decides what to do with it.

What happens if a function has no return?

If a function does not include a `return` statement, Python automatically returns the special value `None`. This trips up many beginners who expect a value but get `None` instead.

“`python def greet(name): print(f”Hi, {name}”)

value = greet(“Sam”) print(value)

“`

Here `greet` prints but does not return, so `value` becomes `None`. The full mechanics of `return`, including returning multiple values as a tuple, are covered in .

How do default parameters work?

A default parameter gives a parameter a fallback value, used when the caller does not supply that argument. You set defaults in the definition with `=`.

“`python def power(base, exponent=2): return base ** exponent

print(power(5)) # uses default exponent of 2 print(power(5, 3)) # overrides the default

“`

The form `def f(x, y=10)` means `x` is required and `y` is optional. One rule: parameters with defaults must come after parameters without them.

What is the difference between positional and keyword arguments?

Positional arguments are matched to parameters by their order. Keyword arguments are matched by name, so order does not matter.

“`python def describe(name, role): return f”{name} works as a {role}”

print(describe(“Ravi”, “engineer”)) # positional print(describe(role=”engineer”, name=”Ravi”)) # keyword

“`

Keyword arguments make calls easier to read, especially when a function has many parameters or when several of them are booleans.

What are *args and **kwargs?

Sometimes you do not know in advance how many arguments a function will receive. Python provides two tools for this:

  • `*args` collects any extra positional arguments into a tuple.
  • `kwargs` collects any extra keyword** arguments into a dictionary.

“`python def total(*args): return sum(args)

print(total(1, 2, 3)) print(total(10, 20, 30, 40))

def profile(**kwargs): for key, value in kwargs.items(): print(f”{key}: {value}”)

profile(name=”Aisha”, role=”developer”, city=”Mumbai”)

“`

The names `args` and `kwargs` are convention, not a requirement. It is the `*` and `**` that matter.

How does variable scope work in functions?

Scope determines where a variable can be seen. A variable created inside a function is local to that function. What happens inside the function stays inside the function, unless you `return` it. Code outside the function cannot see local variables.

“`python def make_message(): secret = “inside the function” return secret

result = make_message() print(result)

“`

A global variable is defined outside any function and can be read inside functions:

“`python greeting = “Hello” # global

def show(): print(greeting) # can read the global

show()

“`

This local-by-default behavior is a feature, not an inconvenience. It means a function cannot accidentally clobber a variable somewhere else in your program. To go further, read .

What are docstrings and why use them?

A docstring is a string written as the first line inside a function body. It documents what the function does. Tools and the built-in `help()` function read it.

“`python def calculate_tax(amount, rate=0.18): “””Return the tax owed on an amount at the given rate.

amount: the pre-tax value rate: tax rate as a decimal (default 0.18) “”” return amount * rate

print(calculate_tax(1000)) help(calculate_tax)

#

“`

Docstrings cost a few seconds to write and save your future self minutes of re-reading code to remember what it does.

The real value of functions is not reuse. It is naming and containing complexity. The textbook answer is that functions let you avoid retyping code. True, but that misses the deeper point. A well-named function such as `calculate_tax` or `send_welcome_email` lets you stop thinking about *how* something is done and just think about *what* it does. Twenty lines of detail collapse into one meaningful name you can hold in your head. That is why functions make code readable, testable, and changeable all at once: each function is a sealed box with a clear name and a clear input and output, so you can understand it, test it, and modify it without holding the entire program in your mind. Beginners write functions to avoid retyping. Experienced developers write functions to *divide* a hard problem into named, understandable pieces. Even a function called exactly once earns its place if it gives a chunk of logic a name and a boundary. Functions are how you turn an overwhelming wall of code into a set of nameable ideas.

Why do functions matter? The DRY principle

Functions exist to serve three practical goals:

  • DRY (Don’t Repeat Yourself): Write logic once, call it everywhere. Fix a bug in one place instead of ten.
  • Readability: A name like `validate_email(address)` tells the reader the intent immediately.
  • Testability: A function with clear inputs and outputs can be tested in isolation, without running the whole program.

Here is the difference DRY makes:

“`python

print(“USD 100″ + ” converted”) print(“USD 250″ + ” converted”)

def label(amount): return f”USD {amount} converted”

print(label(100)) print(label(250))

“`

What is a lambda function?

A lambda is a small, anonymous function written in a single expression. It has no name and is handy for short, throwaway operations, often passed to functions like `sorted()` or `map()`.

“`python square = lambda x: x ** 2 print(square(6))

pairs = [(“apple”, 3), (“banana”, 1), (“cherry”, 2)] pairs.sort(key=lambda item: item[1]) print(pairs)

“`

Use a `def` function when the logic is more than a line or needs a name. Reach for a lambda only for short, inline expressions.

Quick reference: function concepts and examples

Concept Example What it does
Define `def greet():` Creates a named block of code
Call `greet()` Runs the function
Parameter `def add(a, b):` Names in the definition
Argument `add(3, 4)` Values passed in
Return `return a + b` Sends a value back to the caller
No return function gives `None` Default when `return` is absent
Default `def f(x, y=10):` Optional argument with a fallback
Keyword arg `f(x=1, y=2)` Pass values by name
`*args` `def f(*args):` Collects extra positional args (tuple)
`**kwargs` `def f(**kwargs):` Collects extra keyword args (dict)
Local scope `secret = “x”` inside `def` Variable visible only inside the function
Docstring `”””Explains the function.”””` Documents what the function does
Lambda `lambda x: x ** 2` Small anonymous function
Built-in function Purpose Example output
`len()` Length of a sequence `len(“hi”)` returns `2`
`sum()` Sum of an iterable `sum([1, 2, 3])` returns `6`
`max()` Largest value `max(4, 9, 2)` returns `9`
`sorted()` Sorted list `sorted([3, 1, 2])` returns `[1, 2, 3]`

Run your Python where you control the environment

DarazHost VPS and dedicated servers give developers a real, controllable Python environment. Write, organize, and run well-structured code on guaranteed resources with full root access. As your scripts grow into applications with their own dependencies, virtual environments, and scheduled jobs, you need more than a shared sandbox. DarazHost is the dependable home your Python work needs, backed by 24/7 support, so your functions, modules, and services run exactly as you wrote them. For the full picture of building on infrastructure you control, read our pillar guide: Hosting for Developers: The Complete Guide to a Real Environment You Control.

Putting it all together

Here is a small program that uses most of what this guide covered: a named function, a default parameter, a docstring, a `return` value, and local scope.

“`python def format_invoice(client, amount, currency=”USD”): “””Return a formatted invoice line for a client.””” line = f”{client}: {amount} {currency}” return line

print(format_invoice(“Acme”, 500)) print(format_invoice(“Globex”, 750, “EUR”))

“`

One function. A clear name. A clear input and output. That is the whole idea.

Frequently asked questions

What is a function in Python in simple terms? A function in Python is a named, reusable block of code defined with `def`. You write it once and run it whenever you need by calling its name with parentheses, optionally passing in arguments.

What is the difference between return and print in a function? `print()` displays text on the screen and gives nothing back to your code. `return` sends a value back to the caller so it can be stored in a variable and used later. A function can print without returning, return without printing, or do both.

What does a function return if there is no return statement? It returns `None`. Every Python function returns something. If you do not write an explicit `return`, Python returns the special value `None` automatically.

What is the difference between *args and kwargs?** `*args` collects extra positional arguments into a tuple, while `kwargs` collects extra keyword arguments into a dictionary. Use `*args` when the number of values is unknown and `kwargs` when named options are unknown.

When should I use a lambda instead of def? Use a lambda for a short, single-expression function you need inline, such as a sort key. Use `def` for anything that needs a name, multiple statements, or a docstring.

About the Author

Leave a Reply