Python Functions – Syntax, Types, Parameters & Examples

Introduction

A function is a collection of statements grouped together to perform a particular operation. Instead of writing the same code multiple times, you can define a function once and call it whenever needed. This makes programs more efficient, readable, and easier to maintain.

For example, if you need to calculate the total price of products multiple times in an e-commerce application, you can create a function and reuse it throughout the program.

What are Python Functions?

A function is a named block of code that performs a specific task and can be executed whenever required.

Functions help:

  • Reduce code duplication
  • Improve code readability
  • Simplify debugging
  • Increase code reusability
  • Make programs modular

Example:


def greet():
    print("Welcome to Python")
greet()

Output:

Welcome to Python

In this example:

  • def is used to define a function.
  • greet is the function name.
  • The function is executed using greet().

Why Use Functions?

Without functions:


print("Welcome")
print("Welcome")
print("Welcome")

With functions:


def greet():
    print("Welcome")
greet()
greet()
greet()

Benefits

  • Less code repetition
  • Easier maintenance
  • Better organization
  • Improved readability

Syntax

The basic syntax of a function is:


def function_name():
    # function body

Example:


def display_message():
    print("Hello World")

Calling the Function


display_message()

Output:

Hello World

Components of a Function

A function generally consists of:

1. Function Definition


def greet():

2. Function Body


print("Hello")

3. Function Call


greet()

Function Without Parameters

A function can be created without accepting any input values.

Example:


def welcome():
    print("Welcome to Python Programming")
welcome()

Output:

Welcome to Python Programming

Function With Parameters

Parameters allow functions to receive data.

Example:


def greet(name):
    print("Hello", name)
greet("John")

Output:

Hello John

Here, name is a parameter.

Function With Multiple Parameters

Example:


def add(a, b):
    print(a + b)
add(10, 20)

Output:

30

Function Returning a Value

Functions can return data using the return keyword.

Example:


def square(number):
    return number * number
result = square(5)
print(result)

Output:

25

Difference Between Print and Return

Using Print


def add(a, b):
    print(a + b)

Using Return


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

The return statement allows the result to be stored and reused.

Types of Functions in Python

Python provides two main types of functions:

1. Built-in Functions

Provided by Python.

Examples:


print()
len()
type()
max()
min()

Example:


numbers = [10, 20, 30]
print(len(numbers))

Output:

3

2. User-Defined Functions

Created by programmers.

Example:


def multiply(a, b):
    return a * b
print(multiply(4, 5))

Output:

20

Function Arguments

Arguments are values passed to a function.

Example:


def student(name):
    print(name)
student("Emma")

Output:

Emma

Default Arguments

Functions can have default values.

Example:


def greet(name="Guest"):
    print("Hello", name)
greet()
greet("John")

Output:

Hello Guest
Hello John

Keyword Arguments

Arguments can be passed by name.

Example:


def employee(name, age):
    print(name, age)
employee(age=25, name="David")

Output:

David 25

Arbitrary Arguments (*args)

Allows multiple values.

Example:


def total(*numbers):
    print(sum(numbers))
total(10, 20, 30)

Output:

60

Arbitrary Keyword Arguments (**kwargs)

Allows multiple named arguments.

Example:


def student(**details):
    print(details)
student(name="John", age=20)

Output:

{‘name’: ‘John’, ‘age’: 20}

Local Variables

Variables created inside a function.

Example:


def demo():
    message = "Python"
    print(message)
demo()

Output:

Python

The variable exists only inside the function.

Global Variables

Variables declared outside functions.

Example:


course = "Python"
def show_course():
    print(course)
show_course()

Output:

Python

Calling One Function from Another

Example:


def greet():
    print("Hello")
def welcome():
    greet()
    print("Welcome")
welcome()

Output:

Hello
Welcome

Real-Life Examples:

1. Student Result System


def calculate_total(math, science, english):
    return math + science + english
total = calculate_total(80, 75, 90)
print("Total Marks:", total)

Output:

Total Marks: 245

Schools use similar calculations.

2. E-Commerce Website


def calculate_price(price, quantity):
    return price * quantity
total = calculate_price(500, 3)
print(total)

Output:

1500

Online shopping platforms use functions extensively.

3. Banking System


def check_balance(balance):
    print("Current Balance:", balance)
check_balance(10000)

Output:

Current Balance: 10000

4. Employee Salary Calculation


def calculate_salary(hours, rate):
    return hours * rate
salary = calculate_salary(40, 20)
print(salary)

Output:

800

5. Login Validation


def validate_user(username):
    return username == "admin"
print(validate_user("admin"))

Output:

True

Advantages of Functions

1. Code Reusability

Write once and use multiple times.

2. Better Readability

Programs become easier to understand.

3. Easier Maintenance

Changes need to be made in only one place.

4. Reduced Code Duplication

Avoid writing repetitive code.

5. Modular Programming

Programs can be divided into smaller sections.

Common Mistakes

1. Forgetting Parentheses

Incorrect:


greet

Correct:


greet()

2. Missing Colon

Incorrect:


def greet()

Output:

SyntaxError

Correct:


def greet():

3. Wrong Indentation

Incorrect:


def greet():
print("Hello")

Output:

IndentationError

Correct:


def greet():
    print("Hello")

4. Forgetting Return Statement

Incorrect:


def add(a, b):
    a + b

Correct:


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

5. Incorrect Number of Arguments

Incorrect:


def add(a, b):
    return a + b
    add(10)

Output:

TypeError

Best Practices

1. Use Meaningful Function Names


def calculate_salary():

Instead of:


def cs():

2. Keep Functions Small

Each function should perform one task.

3. Add Comments When Necessary


def calculate_tax():
    # Calculate GST

4. Return Values Instead of Printing

Prefer:


return total

Over:


print(total)

5. Follow Naming Conventions

Use lowercase names with underscores.


def calculate_total_price():

Conclusion

Python functions are one of the most powerful features of the language. They help organize code into reusable blocks, making programs cleaner, more efficient, and easier to maintain. Whether you’re building a simple calculator, an e-commerce website, a banking system, or a complex web application, functions play a crucial role in structuring your code.

Python Functions – Interview Questions

Q 1: What is a function in Python?
Ans: A function is a reusable block of code that performs a task.
Q 2: How do you define a function?
Ans: Using the def keyword.
Q 3: Can a function return a value?
Ans: Yes, using the return statement.
Q 4: What are function parameters?
Ans: They are values passed to a function.
Q 5: Why are functions important?
Ans: They improve code reusability and readability.

Python Functions – Objective Questions (MCQs)

Q1. Which keyword is used to define a function in Python?






Q2. What will be the output of the following code?

def greet():
print("Hello, Python!")
greet()






Q3. What is the correct way to call a function named myFunction?






Q4. What will the following function return?

def add(a, b):
return a + b
print(add(3, 5))






Q5. Which statement is true about Python functions?






Related Python Tutorials