Python Functions Tutorial: Definition, Types & Examples for Beginners
๐ Functions in Python
Complete Guide
def · Parameters · Return · Lambda · Recursion · *args · **kwargs · Scope
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.
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.
def greet(): print("Hello! Welcome to Python.") greet() # call the function
| Part | Meaning |
|---|---|
| def | Keyword to define a function |
| function_name | Name you give the function |
| parameters | Input values (optional) |
| docstring | Description text (optional) |
| return | Value to send back (optional) |
my_function. Cannot start with a number.| Type | Description | Example |
|---|---|---|
| Built-in | Pre-installed with Python | print(), len() |
| User-defined | Created by programmer | def my_func(): |
| Lambda | Anonymous one-line | lambda x: x*2 |
| Recursive | Calls itself | factorial(n) |
| Nested | Function inside function | def outer(): def inner(): |
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.
| Function | What it does | Example |
|---|---|---|
| print() | Displays output | print("Hi") |
| len() | Returns length | len("Python") → 6 |
| type() | Returns data type | type(5) → int |
| int() | Converts to integer | int("5") → 5 |
| str() | Converts to string | str(10) → "10" |
| abs() | Absolute value | abs(-5) → 5 |
| max() | Largest value | max(3,7,2) → 7 |
| min() | Smallest value | min(3,7,2) → 2 |
| sum() | Sum of a list | sum([1,2,3]) → 6 |
| range() | Number sequence | range(1,6) |
print(len("Python")) # 6 print(max(3, 9, 1)) # 9 print(abs(-42)) # 42 print(sum([1,2,3,4])) # 10
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.
def say_hello(): print("Hello from my function!") say_hello() # Hello from my function! say_hello() # Call again — works!
Hello from my function!
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.
def greet(name): print("Hello,", name) greet("Ali") # Hello, Ali greet("Sara") # Hello, Sara
def add(a, b): print("Sum:", a + b) add(5, 3) # Sum: 8 add(10, 20) # Sum: 30
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.
def square(n): return n * n print(square(5)) # 25 print(square(9)) # 81
def min_max(nums): return min(nums), max(nums) lo, hi = min_max([3, 1, 9, 5]) print("Min:", lo, "Max:", hi)
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.
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
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.
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
Many beginners confuse these two terms. They are very similar but used at different stages.
| Term | Where | Example |
|---|---|---|
| Parameter | In function definition | def add(a, b) ← a, b |
| Argument | When calling function | add(5, 3) ← 5, 3 |
# a, b = PARAMETERS (placeholders) def add(a, b): print(a + b) # 5, 3 = ARGUMENTS (real values) add(5, 3) # 8
def area(l, w): return l * w print(area(5, 3)) # 15
def check_pwd(pwd): if len(pwd) >= 8: return "Strong!" return "Too short!" print(check_pwd("abc")) # Too short! print(check_pwd("mypass99")) # Strong!
def discount(price, pct): off = price * pct / 100 return price - off print(discount(1000, 10)) # 900.0 print(discount(500, 20)) # 400.0
400.0
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.
def outer(): msg = "Hello from outer!" def inner(): print(msg) # accesses outer variable inner() # call inner function outer()
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.
def factorial(n): if n == 1: # base case return 1 return n * factorial(n - 1) print(factorial(5)) # 120 print(factorial(3)) # 6
6
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.
def greet(name, msg="Good morning!"): print(name, "-", msg) greet("Ali") # uses default greet("Sara", "Good evening!") # overrides
Sara - Good evening!
def f(a=1, b) is wrong — def f(b, a=1) is correct.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.
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)
Sara 17 B
*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:def total(*args): print("Sum:", sum(args)) total(1, 2, 3) # Sum: 6 total(10, 20, 30) # Sum: 60
def show(**kwargs): for k, v in kwargs.items(): print(k, ":", v) show(name="Ali", age=18, city="Karachi")
age : 18
city : Karachi
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.
| Type | Where defined | Accessible |
|---|---|---|
| Local | Inside function | Only in that function |
| Global | Outside function | Everywhere |
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
global x"""Calculates and returns the area."""greet() # NameError! def greet(): print("Hello")
def add(a, b): return a + b add(5) # TypeError: missing argument
def f(): x = 10 f() print(x) # NameError: x not defined
def square(n): n * n # forgot return! print(square(5)) # None (not 25)
calculate_tax() not ct()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!
| Topic | Key Point |
|---|---|
| def | Defines a function |
| Parameters | Input placeholders in definition |
| Arguments | Real values passed in call |
| return | Sends value back to caller |
| lambda | Anonymous one-line function |
| *args | Multiple positional arguments |
| **kwargs | Multiple keyword arguments |
| Scope | Local vs Global variables |
| Recursion | Function calls itself |
| Nested | Function inside a function |
Comments
Post a Comment