Python Functions Explained: A Beginner’s Guide with Code Examples

← Back to Home

Python Functions Explained: A Complete Beginner to Pro Guide

Functions are one of the most important building blocks in Python. They help you write cleaner, reusable, and organized code, no matter whether you're building small scripts or full applications.

If you're new to Python, think of a function as a named mini-program inside your main program. You create it once and use it whenever you need it—just like using a button to perform a task.



What is a Function in Python?

A function is a reusable block of code that performs a specific task. It only runs when you call (execute) it, and it can accept input (parameters) and return output using the return keyword.

📌 Key Points:

  • A function runs only when it is called.
  • It can receive values (parameters).
  • It can return a result using return.
  • In Python, you create a function using the  def keyword.

See a basic example below:

def welcome():
    print("Hello from Python!")


Basic Anatomy of a Function

def function_name(parameters):
    # code block
    return result

Code Diagram


+------------------------------+
| def say_hello(name):        |  ← Function Definition
|     print("Hi,", name)      |  ← Function Body
+------------------------------+

             ↓ Function Call

+-----------------------+
| say_hello("Rohan")    | → Output: Hi, Rohan
+-----------------------+


Why Use Functions?

Functions make coding easier by helping you:

  • 🧩 Break large tasks into smaller steps
  • 🔁 Reuse code without rewriting it
  • 📘 Make programs easier to read and modify
  • 🛠️ Debug and maintain code effortlessly


Creating Your First Function

Let's start with a simple function:

def show_message():
    print("Welcome to Python Functions!")

Now call the function:

show_message()

Output:

Welcome to Python Functions!


Function with Parameters

Parameters allow you to send data into a function.

def greet_user(name):
    print(f"Hello, {name}!")

greet_user("Sara")

🖨️Output:

Hello, Sara!


Reusability Example

def greet(name):
    print(f"Hi, {name}!")

greet("Aman")
greet("Diya")
greet("Isha")

🖨️ Output:

Hi, Aman!
Hi, Diya!
Hi, Isha!


Returning Values from Functions

def multiply(a, b):
    return a * b

result = multiply(6, 4)
print(result)

🖨️Output:

24


Function with Conditional Logic

def is_adult(age):
    if age >= 18:
        return True
    else:
        return False

print(is_adult(20))   # True
print(is_adult(15))   # False


Default Parameters

def welcome(name="Guest"):
    print(f"Welcome, {name}!")

welcome()           # Welcome, Guest!
welcome("Rita")     # Welcome, Rita!


Keyword Arguments

def details(name, city):
    print(f"{name} lives in {city}")

details(city="Delhi", name="Farhan")


*args and **kwargs


*args - Multiple Positional Arguments

def total_marks(*scores):
    return sum(scores)

print(total_marks(75, 82, 90))

**kwargs - Multiple Keyword Arguments

def profile(**info):
    print(info)

profile(name="Nisha", age=21, hobby="Chess")


Returning Multiple Values

def calculate(a, b):
    return a+b, a-b

s, d = calculate(10, 3)
print(s, d)


Using Docstrings

def add(a, b):
    """Adds two numbers and returns the result."""
    return a + b


Lambda (Anonymous) Functions

square = lambda x: x * x
print(square(7))


Local vs Global Variables

x = 50  # global variable

def show():
    x = 10
    print("Inside:", x)

show()
print("Outside:", x)


Flowchart: How a Function Works

[Start]
   ↓
Define Function → [Call Function?] — No → [End]
                          ↓ Yes
                    Execute Code Block
                          ↓
                     Return Value
                          ↓
                        [End]

See this flowchart visually below:




Watch and Learn

Prefer learning visually? Check out this helpful video:



Final Tip

Functions make your Python code modular, testable, and easier to scale. The more you practice writing them, the more confident you will become as a Python developer.



Your Turn

Create your own functions! Build calculators, converters, mini-apps—anything. Functions will always be part of your journey as a Python programmer.



Frequently Asked Questions (FAQ)

1. Can a function return multiple values?

Yes, Python allows returning multiple values separated by commas. They come back as a tuple.

2. Are parameters and arguments the same thing?

No. Parameters are in the function definition, arguments are the values you pass.

3. Can functions call other functions?

Absolutely! This is common in larger programs.

4. What happens if I don’t use return?

The function returns None by default.



Ready to Learn More?

Continue your Python journey! Click the next lesson below and keep practicing.