Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Types of Exception
    • Exception Handling
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python: Introduction to Functions

Python Functions Introduction - Complete Guide

Learn what functions are in Python, why they are important, and how to use them.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • What is a Function?
  • Why Use Functions?
  • Function Basics
  • Defining a Function
  • Calling a Function
  • Parameters vs Arguments
  • Return Values
  • Common Mistakes
  • Try It Yourself
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You'll Learn Here
  • What is a function — definition and purpose
  • Why use functions — benefits of using functions
  • Function basics — defining and calling functions
  • Parameters vs arguments — the difference
  • Return values — getting results from functions
  • Common mistakes — and how to avoid them

What is a Function?

A function is a block of reusable code that performs a specific task. Think of it like a machine: you give it inputs, it does some work, and it gives you back a result.

Definition: A function is a named block of code that can be called (invoked) to perform a specific operation. Functions help organize code, reduce repetition, and make programs easier to understand and maintain.

Here's a simple analogy:

  • Imagine you have a recipe (the function)
  • You gather ingredients (parameters)
  • You follow the steps (function body)
  • You get a dish (return value)

💡 Key concept: Functions are the building blocks of programs. They help you write code that is organized, reusable, and easier to debug.

Why Use Functions?

1

Benefits of Using Functions

# WITHOUT functions (repetitive code)
# Calculate area of rectangle 1
length1 = 5
width1 = 3
area1 = length1 * width1
print(f"Area 1: {area1}")

# Calculate area of rectangle 2
length2 = 7
width2 = 4
area2 = length2 * width2
print(f"Area 2: {area2}")

# Calculate area of rectangle 3
length3 = 6
width3 = 8
area3 = length3 * width3
print(f"Area 3: {area3}")

# WITH functions (reusable code)
def calculate_area(length, width):
    """Calculate the area of a rectangle"""
    return length * width

# Now we can reuse this function many times
area1 = calculate_area(5, 3)
area2 = calculate_area(7, 4)
area3 = calculate_area(6, 8)

print(f"Area 1: {area1}")
print(f"Area 2: {area2}")
print(f"Area 3: {area3}")

# Benefits of functions:
# 1. Code reusability — write once, use many times
# 2. Easier to read — code is organized
# 3. Easier to debug — fix in one place
# 4. Easier to test — test in isolation
# 5. Reduces duplication — DRY principle

Benefits:

  • Reusability — write code once, use it everywhere
  • Organization — group related code together
  • Readability — code is easier to understand
  • Maintainability — changes in one place
  • Testing — test each function independently

Quick Check: What is the main benefit of using functions? (Answer: Code reusability and organization)

Function Basics

2

Understanding Function Structure

# Basic function structure
def function_name(parameter1, parameter2):
    """Optional docstring explaining the function"""
    # Function body - code that does the work
    result = parameter1 + parameter2
    return result  # Optional return value

# Let's look at each part:
# 1. def — keyword to define a function
# 2. function_name — name you give to the function
# 3. parameters — inputs the function accepts
# 4. docstring — documentation (optional but recommended)
# 5. body — indented block of code
# 6. return — output value (optional)

# Simple example
def greet(name):
    """Greet a person by name"""
    return f"Hello, {name}!"

# Calling the function
message = greet("Alice")
print(message)  # Hello, Alice!

Function components:

  • def — keyword to define a function
  • name — function name (follow naming rules)
  • parameters — optional inputs
  • docstring — documentation string
  • body — indented code block
  • return — optional output value

Quick Check: What keyword is used to define a function? (Answer: def)

Defining a Function

3

How to Define a Function

# Function with no parameters
def say_hello():
    """Print a greeting"""
    print("Hello, World!")

# Function with one parameter
def greet(name):
    """Greet a person"""
    print(f"Hello, {name}!")

# Function with multiple parameters
def add(a, b):
    """Add two numbers"""
    return a + b

# Function with default parameter
def greet_user(name="Guest"):
    """Greet a user with a default name"""
    return f"Hello, {name}!"

# Function with multiple return values
def get_user_info():
    """Return multiple values as a tuple"""
    return "Alice", 25, "Engineer"

# Function with type hints (Python 3.5+)
def multiply(a: int, b: int) -> int:
    """Multiply two integers"""
    return a * b

Key points:

  • Function definition starts with def
  • Function name should be descriptive
  • Parameters are optional
  • Docstrings are recommended
  • Return statement is optional

Quick Check: What is a docstring? (Answer: A string that documents what the function does)

Calling a Function

4

How to Call a Function

# Define a function first
def calculate_total(price, quantity):
    """Calculate total cost"""
    return price * quantity

# Calling the function
# Syntax: function_name(arguments)

# Call with positional arguments
total = calculate_total(10, 3)  # 10 * 3 = 30

# Call with keyword arguments
total = calculate_total(price=10, quantity=3)

# Call with mixed arguments (positional first)
total = calculate_total(10, quantity=3)

# Calling functions that don't return anything
def show_message():
    print("This is a message")

show_message()  # Just prints, no return value

# Calling functions with default parameters
def greet(name="Guest"):
    return f"Hello, {name}!"

print(greet())        # Hello, Guest!
print(greet("Alice")) # Hello, Alice!

Calling methods:

  • Positional arguments — match order
  • Keyword arguments — specify parameter name
  • Default arguments — optional values
  • Mixed arguments — positional first, then keyword

Quick Check: What is the syntax to call a function? (Answer: function_name(arguments))

Parameters vs Arguments

5

Understanding the Difference

# Parameters are defined in the function
def greet(name, greeting):  # name and greeting are parameters
    return f"{greeting}, {name}!"

# Arguments are passed when calling
result = greet("Alice", "Hello")  # "Alice" and "Hello" are arguments

# Let's break it down:
# 1. Parameters — placeholders defined in the function
# 2. Arguments — actual values passed when calling

# Example with default parameters
def greet(name, greeting="Hello"):  # greeting has a default value
    return f"{greeting}, {name}!"

# Different ways to call
print(greet("Alice"))              # Uses default greeting
print(greet("Bob", "Hi"))          # Overrides default

# Keyword arguments
def create_user(name, age, city):
    return f"{name} is {age} years old from {city}"

# Order matters for positional arguments
print(create_user("Alice", 25, "NYC"))

# Order doesn't matter for keyword arguments
print(create_user(age=25, name="Alice", city="NYC"))

Key differences:

  • Parameters — defined in the function
  • Arguments — passed when calling
  • Positional — order matters
  • Keyword — name matters, order doesn't
  • Default — optional parameters

Quick Check: What is the difference between a parameter and an argument? (Answer: Parameters are defined in the function; arguments are passed when calling)

Return Values

6

Getting Results from Functions

# Function with return value
def add(a, b):
    return a + b

# Function with no return (returns None)
def print_message(msg):
    print(msg)
    # No return statement — returns None

# Function with multiple return values
def get_user():
    return "Alice", 25, "Engineer"

# Using return values
result = add(5, 3)
print(result)  # 8

# Multiple return values
name, age, job = get_user()
print(name, age, job)  # Alice 25 Engineer

# Return early
def validate_age(age):
    if age < 0:
        return "Invalid age"
    if age < 18:
        return "Too young"
    return "Valid age"

print(validate_age(-5))  # Invalid age
print(validate_age(15))  # Too young
print(validate_age(25))  # Valid age

Return key points:

  • return — sends a value back to the caller
  • Functions without return return None
  • Can return multiple values as a tuple
  • Early return — exit the function early
  • Return stops the function execution

Quick Check: What does a function return if there is no return statement? (Answer: None)

Common Mistakes

7

Things to Watch Out For

Forgetting to Call the Function

# WRONG — referencing without calling
def greet():
    return "Hello"
print(greet)  # Prints function object, not the result

# CORRECT — call with parentheses
print(greet())  # Hello

Missing Colon or Indentation

# WRONG — missing colon
# def greet(name)  # SyntaxError

# WRONG — incorrect indentation
# def greet(name):
# print("Hello")  # IndentationError

# CORRECT
def greet(name):
    print("Hello")

Not Returning a Value When Needed

# WRONG — no return when needed
def add(a, b):
    result = a + b
    # Missing return

# CORRECT
def add(a, b):
    return a + b

Quick Check: What is the most common mistake with functions? (Answer: Forgetting to call the function with parentheses)

Try It Yourself

Experiment with functions in the editor below. Modify the code and see what happens.

Loading Pyodide... 0%
Python Code Editor
========================================
FUNCTIONS INTRODUCTION PRACTICE
========================================

1. SIMPLE FUNCTION
Hello, Alice!

2. MULTIPLE PARAMETERS
Area: 15

3. DEFAULT PARAMETER
Welcome, Guest!
Welcome, Bob!

4. MULTIPLE RETURN VALUES
Alice is 25 years old, works as Engineer

5. EARLY RETURN
Age -5: Invalid
Age 15: Too young
Age 25: Valid

Functions introduction practice complete!
🏆

You've Got It!

You now understand what functions are, why they are important, and how to define and call them. This is the foundation for all function topics!

Quick Quiz

Test what you've learned:

1. What keyword is used to define a function?
2. What does a function without a return statement return?
3. What is the difference between parameters and arguments?
4. How do you call a function?
5. What is the purpose of a docstring?

Frequently Asked Questions

What is a function in Python? ▼

A function is a reusable block of code that performs a specific task. Functions help organize code, reduce repetition, and make programs easier to understand.

Why should I use functions? ▼

Functions make your code reusable, organized, readable, maintainable, and easier to test. They follow the DRY (Don't Repeat Yourself) principle.

What is the difference between a parameter and an argument? ▼

A parameter is a variable defined in the function definition. An argument is the actual value passed when the function is called.

What does a function return if there is no return statement? ▼

A function without a return statement returns None. This is the default return value in Python.

What's a common interview question about functions? ▼

Common questions include: "What is the difference between a parameter and an argument?" and "What is a function and why use it?"

Can a function return multiple values? ▼

Yes, Python functions can return multiple values as a tuple. You can then unpack them into separate variables.

Where to Go From Here

Now that you understand the basics of functions, check out these related topics:

Modular Programming

Learn how functions enable modular programming.

Learn More →

Types of Functions

Understand built-in vs user-defined functions.

Learn More →

Function Arguments

Master different types of function arguments.

Learn More →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
Previous: Exception Assignments Next: Modular Programming →