Functions
A function is a reusable block of code designed to perform a specific task.
Python Functions
At CIIT Training Institute, functions are taught as one of the most important concepts in Python programming because they help developers write clean, reusable and organized code.
Instead of writing the same logic repeatedly, we can place that logic inside a function and call the function whenever we need it.
What is a Function?
A function is a named block of code that performs a particular task.
For example, instead of writing:
print("Welcome to CIIT 📩")
print("Welcome to CIIT 📩")
print("Welcome to CIIT 📩")
We can create a function and reuse it:
def welcome():
print("Welcome to CIIT 📩")
welcome()
welcome()
welcome()
Output
Welcome to CIIT 📩
Welcome to CIIT 📩
Welcome to CIIT 📩
This makes the program easier to maintain and reuse.
Why Do We Use Functions?
- To avoid code duplication.
- To make code reusable.
- To divide a large program into smaller parts.
- To improve code readability.
- To simplify debugging and testing.
- To make applications easier to maintain.
Function Concept
Function Syntax
def function_name():
# function body
The keyword def is used to define a
function.
Example:
def greet():
print("Hello Python")
greet()
Output
Hello Python
Function Definition
A function definition tells Python what the function should do.
def calculate_sum():
a = 10
b = 20
print(a + b)
The function does not execute simply because it has been defined.
Calling a Function
To execute a function, we need to call it.
def calculate_sum():
a = 10
b = 20
print(a + b)
calculate_sum()
Output
30
Function Reusability
One of the biggest advantages of functions is reusability.
def welcome():
print("Welcome to CIIT Institute🤓📩")
welcome()
welcome()
welcome()
Output
Welcome to CIIT Institute🤓📩
Welcome to CIIT Institute🤓📩
Welcome to CIIT Institute🤓📩
Functions With Parameters
Parameters allow us to send information into a function.
def greet(name):
print("Hello", name)
greet("Sam")
Output
Hello Sam
Here name is the parameter and
"Sam" is the argument.
Multiple Parameters
def add(a, b):
print(a + b)
add(10, 20)
Output
30
Returning a Value
A function can return a result using the
return statement.
def add(a, b):
return a + b
result = add(10, 20)
print(result)
Output
30
The returned value can be stored in a variable and used elsewhere in the program.
print() vs return
| print() | return |
|---|---|
| Displays a value on the screen. | Sends a value back to the caller. |
| Mainly used for displaying output. | Mainly used when the result needs further processing. |
| Does not return the displayed value as the function result. | Ends the function execution and returns the specified value. |
def add(a, b):
return a + b
result = add(5, 10)
print(result)
15
Default Parameter
A default parameter has a predefined value. If the caller does not provide a value, Python uses the default value.
def greet(name="Student"):
print("Hello", name)
greet()
greet("Sam")
Output
Hello Student
Hello Sam
Keyword Arguments
Keyword arguments allow us to pass values using parameter names.
def student(name, course):
print("Name:", name)
print("Course:", course)
student(
name="Sam",
course="Python"
)
Output
Name: Sam
Course: Python
Multiple Return Values
Python functions can return multiple values.
def calculate(a, b):
addition = a + b
subtraction = a - b
return addition, subtraction
add, sub = calculate(20, 10)
print("Addition:", add)
print("Subtraction:", sub)
Output
Addition: 30
Subtraction: 10
Local Variable
A variable created inside a function is generally local to that function.
def show_name():
name = "Sam"
print(name)
show_name()
Output
Sam
Global Variable
A variable created outside a function has a broader scope and can generally be read inside the function.
course = "Python"
def show_course():
print(course)
show_course()
Output
Python
Function Documentation
A function can contain a documentation string, commonly called a docstring.
def add(a, b):
"""Return the sum of two numbers."""
return a + b
print(add(10, 20))
Output
30
Example: Calculator 🤓📩
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
print("Addition:", add(10, 5))
print("Subtraction:", subtract(10, 5))
print("Multiplication:", multiply(10, 5))
Output
Addition: 15
Subtraction: 5
Multiplication: 50
A large application can be divided into multiple small functions like this.
Example: Student Result 🤓🔓
def calculate_percentage(marks, total):
return (marks / total) * 100
percentage = calculate_percentage(450, 500)
print("Percentage:", percentage)
Output
Percentage: 90.0
Function Best Practices
- Give functions meaningful names.
- Keep functions focused on one main task.
- Use parameters instead of repeating hard-coded values.
- Use return values when the result needs further processing.
- Keep functions small and readable.
- Add documentation for complex functions.
Common Mistakes in Functions
| Mistake | Explanation |
|---|---|
Forgetting def
|
Python requires def
to define a normal function.
|
| Incorrect indentation | Function body must be properly indented. |
| Defining but not calling function | The function will not execute until it is called. |
| Wrong number of arguments | The function call must match the required parameters unless defaults or flexible arguments are used. |
| Confusing print and return |
print() displays a value,
while return sends a
value back to the caller.
|
Important Interview Points
- Functions are reusable blocks of code.
-
defis used to define a function. - A function executes when it is called.
- Parameters receive values passed to a function.
-
returnsends a result back to the caller. - Python supports default and keyword arguments.
- Functions help divide large applications into smaller reusable components.
CIIT Learning Point
Remember:
A good function should perform a clear task and should
be reusable. Learn def, parameters,
arguments, return, default arguments and
keyword arguments properly. These concepts are used
throughout real-world Python applications.
CIIT Practice Tasks
-
Create a function named
greet()that prints "Hello Python". - Create a function that accepts two numbers and returns their sum.
- Create a function to calculate the area of a rectangle.
- Create a function that accepts a student's marks and returns the percentage.
- Create a function with a default parameter for the course name.
- Create a calculator using separate functions for addition, subtraction, multiplication and division.
- Create a function that accepts a list of numbers and returns the largest number.
Summary :
A Python function is a reusable block
of code designed to perform a specific task. Functions
are defined using def and executed by
calling their name. Parameters and arguments allow us
to pass information into functions, while
return allows a function to send a result
back to the caller. Python supports default arguments,
keyword arguments, multiple return values and both
local and global variables. Functions help make
applications more readable, reusable, maintainable
and easier to test.