Python Functions Tutorial: Definition, Types & Examples for Beginners

Functions in Python

๐Ÿ Functions in Python
Complete Guide

def · Parameters · Return · Lambda · Recursion · *args · **kwargs · Scope

Section 01
Introduction to Functions

A function is a reusable block of code that performs a specific task. Instead of writing the same code multiple times, you write it once inside a function and call it whenever needed. Functions make programs shorter, organised, easy to read, and much easier to debug and maintain.

Think of a function like a machine — you give it input, it processes, and returns output. Python's built-in print() is itself a function. You just call it and it works every time.

๐Ÿ’ก Why use functions? Write once, use many times. Functions are the backbone of every Python program — small or large.
Section 02
What is a Function in Python?

A function in Python is a named block of code defined using the def keyword. It runs only when it is called. A function can accept input values (parameters), perform operations, and return output. Functions help avoid repetition and break programs into small, manageable pieces.

๐Ÿ’ป Example:
Python
def greet():

    print("Hello! Welcome to Python.")

greet()   # call the function
๐Ÿ‘† Output:
Hello! Welcome to Python.
Defined with def keyword
Only runs when called by name
Can be called any number of times
Section 03
Syntax of a Function
๐Ÿ“‹ Syntax:
def function_name(parameters): """Optional docstring""" statement(s) return value # optional
PartMeaning
defKeyword to define a function
function_nameName you give the function
parametersInput values (optional)
docstringDescription text (optional)
returnValue to send back (optional)
⚠️ Function name rules — use lowercase with underscores: my_function. Cannot start with a number.
Section 04
Types of Functions in Python
TypeDescriptionExample
Built-inPre-installed with Pythonprint(), len()
User-definedCreated by programmerdef my_func():
LambdaAnonymous one-linelambda x: x*2
RecursiveCalls itselffactorial(n)
NestedFunction inside functiondef outer(): def inner():
Section 05
Built-in Functions

Built-in functions come pre-installed with Python. You do not need to define them — just call them directly. Python has over 60 built-in functions for math, strings, lists, I/O, and more.

FunctionWhat it doesExample
print()Displays outputprint("Hi")
len()Returns lengthlen("Python") → 6
type()Returns data typetype(5) → int
int()Converts to integerint("5") → 5
str()Converts to stringstr(10) → "10"
abs()Absolute valueabs(-5) → 5
max()Largest valuemax(3,7,2) → 7
min()Smallest valuemin(3,7,2) → 2
sum()Sum of a listsum([1,2,3]) → 6
range()Number sequencerange(1,6)
๐Ÿ’ป Example:
Python
print(len("Python"))    # 6

print(max(3, 9, 1))     # 9

print(abs(-42))         # 42

print(sum([1,2,3,4]))  # 10
Section 06
User-defined Functions

User-defined functions are functions you create yourself using def. You give the function a name, define what it should do, and call it whenever needed. These functions help organise code into logical, reusable blocks.

๐Ÿ’ป Example:
Python
def say_hello():

    print("Hello from my function!")

say_hello()    # Hello from my function!

say_hello()    # Call again — works!
๐Ÿ‘† Output:
Hello from my function!
Hello from my function!
๐Ÿ’ก The function body runs only when called. You can call it as many times as you want.
Section 07
Functions with Parameters

Parameters are variables listed in the function definition parentheses. They allow the function to accept input values. This makes functions flexible — the same function can work with different values each time it is called.

๐Ÿ’ป One parameter:
Python
def greet(name):

    print("Hello,", name)

greet("Ali")    # Hello, Ali

greet("Sara")   # Hello, Sara
๐Ÿ’ป Multiple parameters:
Python
def add(a, b):

    print("Sum:", a + b)

add(5, 3)     # Sum: 8

add(10, 20)   # Sum: 30
Section 08
Functions with Return Value

The return statement sends a value back from the function. Without return, the function just does an action. With return, the function gives a result you can store and use elsewhere in your program.

๐Ÿ’ป Single return:
Python
def square(n):

    return n * n

print(square(5))   # 25

print(square(9))   # 81
๐Ÿ’ป Multiple return values:
Python
def min_max(nums):

    return min(nums), max(nums)

lo, hi = min_max([3, 1, 9, 5])

print("Min:", lo, "Max:", hi)
๐Ÿ‘† Output:
Min: 1 Max: 9
๐Ÿ’ก After return runs, the function stops immediately. Any code after it is ignored.
Section 09
Lambda Functions

A lambda function is a small, anonymous (nameless) function written in one line. It is used for short, simple operations. Lambda functions can take any number of parameters but only one expression.

๐Ÿ“‹ Syntax:
lambda parameters : expression
๐Ÿ’ป Examples:
Python
square  = lambda x: x ** 2

add     = lambda a, b: a + b

is_even = lambda n: n % 2 == 0

print(square(5))     # 25

print(add(3, 4))      # 7

print(is_even(8))    # True
๐Ÿ’ก Lambda is great for use inside sorted(), map(), and filter() functions.
Section 10
Function Calling

Calling a function means executing it. You call a function by writing its name followed by parentheses (). If the function needs arguments, pass them inside the parentheses. A function can be called from anywhere in your program.

๐Ÿ’ป Ways to call a function:
Python
def multiply(a, b):

    return a * b

# Call directly in print

print(multiply(3, 4))      # 12

# Store result in variable

ans = multiply(5, 6)

print(ans)                   # 30

# Use in expression

print(multiply(2, 3) + 10)  # 16
๐Ÿ“Œ You must define a function before you call it. Calling before defining causes a NameError.
Section 11
Parameters vs Arguments

Many beginners confuse these two terms. They are very similar but used at different stages.

TermWhereExample
ParameterIn function definitiondef add(a, b) ← a, b
ArgumentWhen calling functionadd(5, 3) ← 5, 3
๐Ÿ’ป Example:
Python
# a, b = PARAMETERS (placeholders)

def add(a, b):

    print(a + b)

# 5, 3 = ARGUMENTS (real values)

add(5, 3)    # 8
๐Ÿ’ก Parameters = placeholders in definition. Arguments = real values passed in call.
Section 12
Advantages of Functions
Reusability — Write once, use many times
Modularity — Break large programs into small pieces
Readability — Meaningful names make code clear
Easy debugging — Fix one function without touching others
Less repetition — No copy-paste code needed
Testable — Each function can be tested independently
Organised — Makes large programs easy to manage
๐ŸŒŸ Professional Python developers always use functions. Code without functions is considered poor quality.
Section 13
Real-Life Examples of Functions
๐Ÿงฎ 1. Rectangle Area:
Python
def area(l, w):

    return l * w

print(area(5, 3))   # 15
๐Ÿ” 2. Password Validator:
Python
def check_pwd(pwd):

    if len(pwd) >= 8:

        return "Strong!"

    return "Too short!"

print(check_pwd("abc"))       # Too short!

print(check_pwd("mypass99"))  # Strong!
๐Ÿ’ฐ 3. Discount Calculator:
Python
def discount(price, pct):

    off = price * pct / 100

    return price - off

print(discount(1000, 10))  # 900.0

print(discount(500, 20))   # 400.0
๐Ÿ‘† Output:
900.0
400.0
Section 14
Nested Functions

A nested function is a function defined inside another function. The inner function can access variables from the outer function. Nested functions are useful for helper logic, closures, and hiding code that should only be used inside one function.

๐Ÿ’ป Example:
Python
def outer():

    msg = "Hello from outer!"

    def inner():

        print(msg)   # accesses outer variable

    inner()   # call inner function

outer()
๐Ÿ‘† Output:
Hello from outer!
๐Ÿ“Œ The inner function is not accessible from outside the outer function. It only exists within it.
Section 15
Recursive Functions

A recursive function calls itself inside its own body to solve smaller versions of the same problem. Every recursive function must have a base case — a condition that stops the recursion. Without it, the function runs forever and crashes with a RecursionError.

๐Ÿ’ป Factorial:
Python
def factorial(n):

    if n == 1:             # base case

        return 1

    return n * factorial(n - 1)

print(factorial(5))   # 120

print(factorial(3))   # 6
๐Ÿ‘† Output:
120
6
⚠️ Always define a base case. Without it → RecursionError (max depth exceeded).
Section 16
Default Parameters

Default parameters are values assigned to parameters in the function definition. If the caller does not provide that argument, the default value is used automatically. This makes functions more flexible — they work with or without certain inputs.

๐Ÿ’ป Example:
Python
def greet(name, msg="Good morning!"):

    print(name, "-", msg)

greet("Ali")                    # uses default

greet("Sara", "Good evening!")  # overrides
๐Ÿ‘† Output:
Ali - Good morning!
Sara - Good evening!
⚠️ Default parameters must come after non-default ones. def f(a=1, b) is wrong — def f(b, a=1) is correct.
Section 17
Keyword Arguments

Keyword arguments are passed with the parameter name explicitly when calling a function. This means you can pass them in any order — Python matches them by name, not by position. This makes function calls more readable and prevents mistakes.

๐Ÿ’ป Example:
Python
def info(name, age, grade):

    print(name, age, grade)

# Normal positional

info("Ali", 18, "A")

# Keyword — any order

info(grade="B", name="Sara", age=17)
๐Ÿ‘† Output:
Ali 18 A
Sara 17 B
Section 18
Variable-length Arguments (*args, **kwargs)

*args lets a function accept any number of positional arguments — stored as a tuple. **kwargs accepts any number of keyword arguments — stored as a dictionary. Use them when you don't know in advance how many arguments will be passed.

▶ *args:
Python
def total(*args):

    print("Sum:", sum(args))

total(1, 2, 3)         # Sum: 6

total(10, 20, 30)      # Sum: 60
▶ **kwargs:
Python
def show(**kwargs):

    for k, v in kwargs.items():

        print(k, ":", v)

show(name="Ali", age=18, city="Karachi")
๐Ÿ‘† Output:
name : Ali
age : 18
city : Karachi
Section 19
Scope of Variables in Functions

Scope defines where a variable is accessible. Variables inside a function are local (only available there). Variables outside are global (available everywhere). This prevents accidental changes to variables in other parts of your program.

TypeWhere definedAccessible
LocalInside functionOnly in that function
GlobalOutside functionEverywhere
๐Ÿ’ป Example:
Python
x = 10    # global

def my_func():

    y = 20    # local

    print(x)   # ✅ can access global

    print(y)   # ✅ can access local

my_func()

# print(y)  ← NameError! y is local
๐Ÿ’ก Use global keyword to modify a global variable inside a function: global x
Section 20
๐Ÿ“Œ Important Notes about Functions
Define a function before calling it
Use lowercase with underscores for function names
return sends value back and exits the function
A function without return gives back None
Parameters are local to the function
You can return multiple values at once
Functions can be passed as arguments to other functions
Write a docstring to describe each function
๐Ÿ“Œ Good docstring example: """Calculates and returns the area."""
Section 21
Common Errors in Functions
❌ Error 1 — Calling before defining:
Python — WRONG
greet()           # NameError!

def greet():

    print("Hello")
❌ Error 2 — Wrong argument count:
Python — WRONG
def add(a, b):

    return a + b

add(5)  # TypeError: missing argument
❌ Error 3 — Accessing local variable outside:
Python — WRONG
def f():

    x = 10

f()

print(x)  # NameError: x not defined
❌ Error 4 — Forgetting return:
Python — WRONG
def square(n):

    n * n          # forgot return!

print(square(5)) # None (not 25)
Section 22
Best Practices for Using Functions
Use clear, meaningful names: calculate_tax() not ct()
Each function should do one thing only
Keep functions short — ideally under 20 lines
Write a docstring explaining what the function does
Avoid using global variables inside functions
Handle edge cases (empty input, zero, None)
Use default parameters for optional inputs
Test each function independently before using
๐Ÿ† Pro Tip: If a function is getting too long or does too many things — split it into smaller functions. This is the Single Responsibility Principle.
Section 23
Conclusion

Functions are the most important building block of Python. They let you write clean, reusable, and organised code. From simple greetings to complex recursion, functions are everywhere in real Python programs.

Mastering functions means mastering Python. Practice daily — with parameters, return values, lambda, and recursion. The more you use them, the more natural they become!

TopicKey Point
defDefines a function
ParametersInput placeholders in definition
ArgumentsReal values passed in call
returnSends value back to caller
lambdaAnonymous one-line function
*argsMultiple positional arguments
**kwargsMultiple keyword arguments
ScopeLocal vs Global variables
RecursionFunction calls itself
NestedFunction inside a function
๐ŸŒŸ Final Tip: Every time you find yourself copying and pasting the same code — that is the perfect sign to create a function!
Python Functions def Lambda Recursion Beginner
Python Functions — Write Once, Use Everywhere!

Comments