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:
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:
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:
Function With Parameters
Parameters allow functions to receive data.
Example:
def greet(name):
print("Hello", name)
greet("John")
Output:
Here, name is a parameter.
Function With Multiple Parameters
Example:
def add(a, b):
print(a + b)
add(10, 20)
Output:
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:
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:
2. User-Defined Functions
Created by programmers.
Example:
def multiply(a, b):
return a * b
print(multiply(4, 5))
Output:
Function Arguments
Arguments are values passed to a function.
Example:
def student(name):
print(name)
student("Emma")
Output:
Default Arguments
Functions can have default values.
Example:
def greet(name="Guest"):
print("Hello", name)
greet()
greet("John")
Output:
Hello John
Keyword Arguments
Arguments can be passed by name.
Example:
def employee(name, age):
print(name, age)
employee(age=25, name="David")
Output:
Arbitrary Arguments (*args)
Allows multiple values.
Example:
def total(*numbers):
print(sum(numbers))
total(10, 20, 30)
Output:
Arbitrary Keyword Arguments (**kwargs)
Allows multiple named arguments.
Example:
def student(**details):
print(details)
student(name="John", age=20)
Output:
Local Variables
Variables created inside a function.
Example:
def demo():
message = "Python"
print(message)
demo()
Output:
The variable exists only inside the function.
Global Variables
Variables declared outside functions.
Example:
course = "Python"
def show_course():
print(course)
show_course()
Output:
Calling One Function from Another
Example:
def greet():
print("Hello")
def welcome():
greet()
print("Welcome")
welcome()
Output:
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:
Schools use similar calculations.
2. E-Commerce Website
def calculate_price(price, quantity):
return price * quantity
total = calculate_price(500, 3)
print(total)
Output:
Online shopping platforms use functions extensively.
3. Banking System
def check_balance(balance):
print("Current Balance:", balance)
check_balance(10000)
Output:
4. Employee Salary Calculation
def calculate_salary(hours, rate):
return hours * rate
salary = calculate_salary(40, 20)
print(salary)
Output:
5. Login Validation
def validate_user(username):
return username == "admin"
print(validate_user("admin"))
Output:
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:
Correct:
def greet():
3. Wrong Indentation
Incorrect:
def greet():
print("Hello")
Output:
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:
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?
Q 2: How do you define a function?
Q 3: Can a function return a value?
Q 4: What are function parameters?
Q 5: Why are functions important?
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?