In the previous section, you learned how Python uses conditional statements and loops to control the flow of a program. As programs become larger, writing the same code repeatedly makes them difficult to read, maintain, and debug.
Imagine creating a program that calculates the area of a circle in several different places. Instead of writing the same formula again and again, it is better to write the code once and reuse it whenever needed.
Python solves this problem using functions.
A function is a reusable block of code that performs a specific task. Once a function is created, it can be called whenever required, reducing repetition and making programs easier to understand.
Functions are one of the most important concepts in Python because almost every real-world Python application is built using functions.
After completing this lesson, you will be able to:
def keyword.A function is a named block of reusable code that performs a particular task.
Instead of writing the same code multiple times, you can write it once inside a function and call that function whenever needed.
Functions improve program organization and make code easier to maintain.
Think of a television remote control.
When you press the Power button, the television turns on. You do not need to know how the television works internally—you simply use the button whenever required.
Similarly, calling a Python function performs a specific task without requiring you to rewrite the code every time.
Without functions, large programs become difficult to read because the same code appears repeatedly.
Functions help solve this problem by allowing developers to reuse code.
Some benefits of using functions include:
| Advantage | Description |
|---|---|
| Code Reusability | Write code once and use it multiple times. |
| Readability | Programs become easier to understand. |
| Maintainability | Changes are made in one place instead of many. |
| Debugging | Errors are easier to locate. |
| Modularity | Programs are divided into smaller manageable parts. |
Python provides two main types of functions.
Built-in functions are already provided by Python. You can use them directly without creating them yourself.
print("Hello")
length = len("Python")
maximum = max(5, 8, 3)
minimum = min(5, 8, 3)
number = abs(-20)
Output
Hello
6
8
3
20
These functions are available automatically after installing Python.
| Function | Purpose |
|---|---|
print() |
Displays output. |
input() |
Accepts user input. |
len() |
Returns the length of an object. |
type() |
Returns the data type. |
max() |
Returns the largest value. |
min() |
Returns the smallest value. |
sum() |
Returns the sum of values. |
round() |
Rounds a number. |
User-defined functions are functions created by programmers using the def keyword.
These functions allow you to perform tasks specific to your application.
defThe def keyword is used to create a function.
def function_name():
statements
A function definition consists of:
def keyword.().:.def welcome():
print("Welcome to Python Programming")
This function has been created, but it has not been executed yet.
A function executes only when it is called.
def welcome():
print("Welcome to Python Programming")
welcome()
Output
Welcome to Python Programming
The statement welcome() calls the function and executes the code inside it.
One of the biggest advantages of functions is code reuse.
def greet():
print("Good Morning!")
greet()
greet()
greet()
Output
Good Morning!
Good Morning!
Good Morning!
The same function can be called as many times as needed without rewriting the code.
Consider the following program.
def display():
print("Inside Function")
print("Program Starts")
display()
print("Program Ends")
Execution Steps
Program Starts is printed.display() is called.Inside Function is printed.Program Ends is printed.Output
Program Starts
Inside Function
Program Ends
def hello():
print("Hello")
This program produces no output because the function is never called.
hello
Use hello() to call the function.
All statements inside a function must be properly indented.
def hello()
This results in a SyntaxError.
Function names should follow Python’s naming rules and should clearly describe the task they perform.
In this section, you learned what Python functions are and why they are important. You explored the advantages of functions, distinguished between built-in and user-defined functions, learned how to define functions using the def keyword, and understood how to call functions and how Python executes them. You also reviewed common beginner mistakes when creating functions. In the next section, you will learn about function parameters, arguments, positional and keyword arguments, default parameter values, variable-length arguments, and how to return values from functions.
In the previous section, you learned how to create and call Python functions using the def keyword. However, most useful functions need to work with different values each time they are called. For example, a calculator function should be able to add different numbers instead of always using fixed values.
Python solves this problem using parameters and arguments. These allow data to be passed into functions, making them flexible and reusable.
In this section, you will learn about function parameters, different types of arguments, default parameter values, variable-length arguments, and how functions return values.
A parameter is a variable defined inside the function declaration. It acts as a placeholder that receives data when the function is called.
def function_name(parameter):
statements
def greet(name):
print("Hello", name)
Here, name is a parameter.
An argument is the actual value passed to a function when it is called.
def greet(name):
print("Hello", name)
greet("Rahul")
Output
Hello Rahul
In this example, "Rahul" is the argument, while name is the parameter.
Positional arguments are assigned to parameters based on their position.
def student(name, age):
print("Name:", name)
print("Age:", age)
student("Neha", 20)
Output
Name: Neha
Age: 20
The first argument is assigned to the first parameter, and the second argument is assigned to the second parameter.
Keyword arguments allow you to specify the parameter name when calling a function.
def student(name, age):
print("Name:", name)
print("Age:", age)
student(age=20, name="Neha")
Output
Name: Neha
Age: 20
Keyword arguments improve readability and allow arguments to be passed in any order.
A default parameter has a predefined value that is used if no argument is provided.
def greet(name="Guest"):
print("Welcome", name)
greet()
greet("Amit")
Output
Welcome Guest
Welcome Amit
If no argument is supplied, the default value is used automatically.
Functions can accept multiple parameters.
def addition(a, b, c):
print(a + b + c)
addition(10, 20, 30)
Output
60
*args)Sometimes you may not know how many arguments will be passed to a function. In such cases, Python provides *args.
def total(*numbers):
print(sum(numbers))
total(10, 20)
total(5, 10, 15, 20)
Output
30
50
The *args parameter collects all positional arguments into a tuple.
**kwargs)The **kwargs parameter collects keyword arguments into a dictionary.
def student(**details):
print(details)
student(name="Rahul", age=20, city="Delhi")
Output
{'name': 'Rahul', 'age': 20, 'city': 'Delhi'}
This is useful when a function needs to accept an unknown number of keyword arguments.
Lists can be passed directly as arguments.
def display(items):
for item in items:
print(item)
fruits = ["Apple", "Banana", "Orange"]
display(fruits)
Output
Apple
Banana
Orange
Dictionaries can also be passed as arguments.
def show(student):
print(student["name"])
print(student["marks"])
data = {
"name": "Neha",
"marks": 92
}
show(data)
Output
Neha
92
returnA function can send a value back to the caller using the return statement.
def square(number):
return number * number
result = square(6)
print(result)
Output
36
The return statement ends the function and sends the calculated value back.
Python allows a function to return more than one value.
def calculate(a, b):
return a + b, a - b
addition, subtraction = calculate(15, 5)
print(addition)
print(subtraction)
Output
20
10
Consider the following program.
def multiply(a, b):
return a * b
result = multiply(4, 5)
print(result)
Execution Steps
multiply() is defined.a and b.return statement sends the result back.result.Output
20
A function call must match the required parameters unless default values or variable-length arguments are used.
return StatementIf a function should produce a result, remember to use return.
Parameters are defined in the function, while arguments are supplied during the function call.
Be careful when modifying lists or dictionaries passed to functions because changes may affect the original object.
Follow Python’s argument ordering rules to avoid syntax errors.
In this section, you learned how Python functions accept data using parameters and arguments. You explored positional arguments, keyword arguments, default parameters, *args, **kwargs, passing lists and dictionaries, and returning values using the return statement. You also learned how functions can return multiple values, followed the execution flow of a function call, and reviewed common beginner mistakes. In the next section, you will apply these concepts by building practical functions such as calculators, prime number checkers, factorial calculators, temperature converters, student grade evaluators, and other reusable programs.
Functions become truly powerful when they are used to solve real programming problems. Instead of writing the same code repeatedly, you can create a function once and call it whenever required.
In this section, you will build practical Python functions that perform common programming tasks such as calculations, checking numbers, converting temperatures, and determining student grades. These examples demonstrate how functions make programs shorter, more organized, and easier to maintain.
The following function adds two numbers and returns the result.
def add(a, b):
return a + b
result = add(15, 25)
print("Sum =", result)
Output
Sum = 40
The function can be reused with different values whenever required.
This function checks whether a number is even or odd.
def even_or_odd(number):
if number % 2 == 0:
return "Even"
return "Odd"
print(even_or_odd(12))
print(even_or_odd(17))
Output
Even
Odd
The following function checks whether a number is prime.
def is_prime(number):
if number <= 1:
return False
for i in range(2, number):
if number % i == 0:
return False
return True
print(is_prime(13))
print(is_prime(18))
Output
True
False
The function returns True if the number is prime; otherwise, it returns False.
This function calculates the factorial of a number.
def factorial(number):
result = 1
for i in range(1, number + 1):
result *= i
return result
print(factorial(5))
Output
120
The following function returns the larger of two numbers.
def maximum(a, b):
if a > b:
return a
return b
print(maximum(18, 25))
Output
25
This function calculates the area of a circle using the formula πr².
def area_of_circle(radius):
pi = 3.14159
return pi * radius * radius
print(area_of_circle(5))
Output
78.53975
The following function converts Celsius to Fahrenheit.
def celsius_to_fahrenheit(celsius):
return (celsius * 9 / 5) + 32
print(celsius_to_fahrenheit(25))
Output
77.0
This function returns a grade based on marks.
def calculate_grade(marks):
if marks >= 90:
return "A"
elif marks >= 75:
return "B"
elif marks >= 60:
return "C"
else:
return "D"
print(calculate_grade(82))
Output
B
This function displays a personalized greeting.
def greet(name):
return "Welcome " + name
print(greet("Rahul"))
Output
Welcome Rahul
This function returns the square of a number.
def square(number):
return number * number
print(square(9))
Output
81
Consider the following program.
def multiply(a, b):
return a * b
answer = multiply(6, 7)
print(answer)
Execution Steps
multiply() is defined.6 and 7.a and b.return statement sends the result back to the caller.answer.Output
42
Choose descriptive names such as calculate_grade(), find_maximum(), or area_of_circle().
Each function should perform one specific task.
If the same logic appears multiple times, move it into a function.
return Statement AppropriatelyReturn values instead of printing them whenever the result needs to be reused.
Use proper indentation, meaningful variable names, and comments where necessary.
print() with return.In this section, you applied Python functions to practical programming problems such as calculators, even-or-odd checking, prime number testing, factorial calculation, finding the maximum of two numbers, calculating the area of a circle, converting temperatures, assigning student grades, greeting users, and finding the square of a number. You also learned function design best practices, reviewed common beginner mistakes, and followed the execution flow of a function call. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on Python Function Parameters & Arguments.
In this lesson, you learned how Python functions help organize programs into reusable and manageable blocks of code. Instead of writing the same code repeatedly, you can create a function once and call it whenever the task needs to be performed.
You explored the difference between built-in functions and user-defined functions, learned how to define functions using the def keyword, and understood how functions execute when they are called. You also learned how to pass data into functions using parameters and arguments, return results using the return statement, and create flexible functions using positional arguments, keyword arguments, default parameters, *args, and **kwargs.
Through practical examples such as calculators, prime number checkers, factorial calculators, temperature converters, and student grade evaluators, you learned how functions improve code reusability, readability, and maintainability.
Functions are one of the most important building blocks of Python programming and are used extensively in almost every Python application.
def keyword is used to define a function.return statement sends a value back to the caller.*args allows a function to accept multiple positional arguments.**kwargs allows a function to accept multiple keyword arguments.A Python function is a named, reusable block of code that performs a specific task.
Built-in functions are provided by Python, while user-defined functions are created by programmers using the def keyword.
def keyword?The def keyword is used to define a new function in Python.
A parameter is a variable defined in the function declaration, while an argument is the actual value passed to the function when it is called.
return statement do?The return statement sends a value back to the caller and immediately ends the function.
Yes. Python functions can return multiple values separated by commas.
*args and **kwargs?*args collects multiple positional arguments into a tuple, while **kwargs collects multiple keyword arguments into a dictionary.
Functions reduce duplicate code, improve readability, simplify maintenance, and make programs modular.
return statement?*args and **kwargs?Create a Python program that uses functions to calculate and display a student's result.
Your program should:
calculate_total() that accepts marks for three subjects and returns the total.calculate_average() that returns the average marks.calculate_grade() that returns a grade based on the average.Enter Marks in English: 85
Enter Marks in Mathematics: 90
Enter Marks in Science: 80
Total Marks: 255
Average Marks: 85.0
Grade: B
Congratulations! You have learned how to create, call, and reuse Python functions. You now understand how to organize programs into reusable components, pass data through parameters and arguments, and return values from functions. These concepts form the foundation for writing modular and maintainable Python programs.
In the next lesson, you will explore Python Function Parameters & Arguments: Complete Guide for Beginners. You will study parameters and arguments in greater depth, including positional-only parameters, keyword-only parameters, unpacking arguments, argument packing, and advanced techniques for designing flexible and reusable functions.