Introduction to Python Functions
Python is one of the most popular programming languages used in web development, automation, artificial intelligence, data science and software development. One of the most important concepts every Python beginner should understand is Functions in Python.
When we start writing Python programs, we often write instructions one after another. This approach works for small programs, but as applications become larger, writing the same code repeatedly makes programs difficult to manage, understand and maintain.
This is where Python functions become important.
A function allows developers to write a block of code once and execute it whenever required. Instead of repeating the same instructions throughout a program, we can organize them into reusable functions.
For example, imagine building a student management system. You might need to calculate student percentages, display student information, validate marks and generate results. Instead of writing the same calculation repeatedly, you can create separate functions for each task.
In this Day 8 lesson of Python & Django Full Stack OJT by Webitya, we will learn:
- What functions are in Python.
- Why functions are important.
- How to create and call functions.
- Parameters and arguments.
- Return statements.
- Difference between print() and return.
- Types of function arguments.
- Default arguments.
- Building reusable functions.
- Practical Python programming examples.
- Best practices for writing functions.
This tutorial is designed for beginners who want to understand Python functions through simple explanations and practical coding examples.
1. What Is a Function in Python?
A function in Python is a reusable block of code designed to perform a particular task.
A function can contain one or more Python statements. Whenever we need to perform that task, we can call the function instead of writing the same code again.
Real-World Example of a Function
Think about a washing machine.
When you use a washing machine:
- You put clothes inside.
- You select a washing mode.
- You press the start button.
- The machine performs the washing process.
- You get clean clothes.
A Python function works in a similar way. It receives information, performs a specific operation and may return a result.
Example: Without Using a Function
Suppose we want to display a welcome message three times.
print("Welcome to Webitya")
print("Welcome to Webitya")
print("Welcome to Webitya")
Output:
Welcome to Webitya Welcome to Webitya Welcome to Webitya
Here, we have written the same instruction three times.
If we need to display this message 50 times, writing the same statement repeatedly is not an efficient approach.
Example: Using a Function
We can solve this problem by creating a function.
def welcome():
print("Welcome to Webitya")
welcome()
welcome()
welcome()
Output:
Welcome to Webitya Welcome to Webitya Welcome to Webitya
Now, we have written the message only once inside the function and called it three times.
Why Do We Use Functions in Python?
Functions provide several advantages:
1. Code Reusability
Write code once and use it multiple times whenever required.
2. Less Code Repetition
Functions help reduce unnecessary repetition in programs.
3. Easy Debugging
When an error occurs, smaller functions make it easier to identify and fix the problem.
4. Better Code Organization
Functions divide large programs into smaller, manageable sections.
5. Easier Maintenance
If we need to modify a particular operation, we can update its function instead of changing the same logic throughout the program.
Remember: Write once, use multiple times!
2. How to Create a Function in Python
Python provides the def keyword to define a function.
The def keyword tells Python that we are creating a new function.
Basic Syntax of a Python Function
def function_name():
# Code to execute
statement
Let's understand each component.
| Component | Meaning |
| def | Keyword used to define a function |
| function_name | Name given to the function |
| () | Parentheses that can contain parameters |
| : | Indicates the beginning of the function body |
| Indentation | Defines the statements inside the function |
Example: Creating a Simple Function
def greet():
print("Hello Students!")
print("Welcome to Python OJT")
greet()
Output:
Hello Students! Welcome to Python OJT
Understanding the Code
Step 1: We use the def keyword to define a function.
Step 2: We give the function the name greet.
Step 3: We write parentheses () after the function name.
Step 4: We use a colon : to start the function body.
Step 5: We write the statements inside the function using proper indentation.
Step 6: We call the function using greet().
What Is Function Calling?
Creating a function does not automatically execute its code.
To execute a function, we must call it using its name followed by parentheses.
Example:
def show_message():
print("Learning Python is easy!")
# Calling the function
show_message()
Output:
Learning Python is easy!
We can call the same function multiple times.
def show_message():
print("Learning Python is easy!")
show_message()
show_message()
show_message()
Output:
Learning Python is easy! Learning Python is easy! Learning Python is easy!
Important Difference:
- Function definition means creating a function.
- Function calling means executing a function.
- A function can be called multiple times.
- Python executes the function when it is called.
3. Understanding Parameters and Arguments in Python
Sometimes, we want a function to work with different values.
For example, imagine that we want to greet different students using their names.
We could create separate functions for every student, but that would create unnecessary code.
Instead, we can create one function and pass different values to it.
To understand this concept, we need to learn two important terms: parameters and arguments.
What Are Parameters?
Parameters are variables written inside the parentheses when defining a function.
They receive information when the function is called.
What Are Arguments?
Arguments are the actual values passed to a function when calling it.
Example: Function with One Parameter
def greet(name):
print("Hello", name)
greet("Aditya")
greet("Rahul")
greet("Priya")
Output:
Hello Aditya Hello Rahul Hello Priya
Understanding the Code
Let's understand what happens here.
def greet(name):
Here, name is a parameter.
greet("Aditya")
Here, "Aditya" is an argument.
Similarly:
- "Rahul" is an argument.
- "Priya" is an argument.
The same function works with different values.
Example: Function with Two Parameters
A function can accept multiple parameters.
def student_details(name, course):
print("Student Name:", name)
print("Course:", course)
student_details("Aditya", "Python OJT")
Output:
Student Name: Aditya Course: Python OJT
In this example:
- name is the first parameter.
- course is the second parameter.
- "Aditya" is the first argument.
- "Python OJT" is the second argument.
The values are passed according to their positions.
Remember: Parameters receive information, while arguments provide the actual information.
4. Understanding the Return Statement in Python
The return statement is one of the most important concepts in Python functions.
The return statement is used to send a result from a function back to the place where the function was called.
In simple words, a function performs a calculation and gives the result back to us.
Example: Addition Using Return
Suppose we want to create a function that adds two numbers.
def add(a, b):
result = a + b
return result
answer = add(10, 20)
print(answer)
Output:
30
Understanding the Code Step by Step
- We create a function named add.
- It accepts two parameters: a and b.
- It adds both values using a + b.
- The result is stored in the result variable.
- The return result statement sends the answer back.
- We store the returned value in the answer variable.
- Finally, we display the result using print().
Why Is Return Important?
The main advantage of return is that we can use the result somewhere else in our program.
For example:
def add(a, b):
return a + b
result = add(10, 20)
print("Addition:", result)
print("After adding 50:", result + 50)
Output:
Addition: 30 After adding 50: 80
Here, we can use the returned value for additional calculations.
Difference Between print() and return
Many beginners confuse print() and return.
Although both are used inside functions, they have different purposes.
| print() | return |
| Displays information on the screen | Sends a value back |
| Mainly used to show output | Used to provide results |
| Does not return the displayed value | Can return values for further use |
| Useful for displaying messages | Useful for calculations and reusable results |
Example Using print()
def add(a, b):
print(a + b)
result = add(10, 20)
print("Stored value:", result)
Output:
30 Stored value: None
Why does this happen?
The function displays 30, but it does not explicitly return a value.
In Python, a function that finishes without a return statement returns None automatically.
Example Using return
def add(a, b):
return a + b
result = add(10, 20)
print("Stored value:", result)
Output:
Stored value: 30
Now, the result is returned and stored in the variable.
Important: Once Python executes a return statement, the function stops executing further statements within that call.
5. Types of Function Arguments in Python
Python allows us to pass arguments in different ways.
Three commonly used types of function arguments are:
- Positional arguments.
- Keyword arguments.
- Default arguments.
Let's understand each one with practical examples.
5.1 Positional Arguments
Positional arguments are passed according to the position of parameters in a function definition.
Example:
def student(name, age):
print("Name:", name)
print("Age:", age)
student("Aditya", 23)
Output:
Name: Aditya Age: 23
Understanding Positional Arguments
The function contains two parameters:
- name
- age
When we call the function:
student("Aditya", 23)
Python assigns:
- "Aditya" to name.
- 23 to age.
The values are assigned according to their positions.
5.2 Keyword Arguments
Keyword arguments allow us to provide values using parameter names.
Example:
def student(name, age):
print("Name:", name)
print("Age:", age)
student(age=23, name="Aditya")
Output:
Name: Aditya Age: 23
Notice that we changed the order of arguments.
This works because we explicitly specify the parameter names.
Difference Between Positional and Keyword Arguments
Positional arguments:
student("Aditya", 23)
Keyword arguments:
student(age=23, name="Aditya")
Both examples produce the same output.
5.3 Default Arguments
A default argument is a parameter that already has a predefined value.
If the caller does not provide a value for that parameter, Python uses its default value.
Example:
def greet(name, course="Python"):
print("Hello", name)
print("Your course is", course)
greet("Aditya")
greet("Rahul", "Django")
Output:
Hello Aditya Your course is Python Hello Rahul Your course is Django
Understanding Default Arguments
In this function:
def greet(name, course="Python"):
The name parameter is required, while course has a default value of "Python".
When we call:
greet("Aditya")
Python automatically uses "Python" as the course.
But when we call:
greet("Rahul", "Django")
Python uses "Django" instead of the default value.
Why Are Default Arguments Useful?
- They reduce repeated values.
- They make functions easier to use.
- They provide flexibility.
- They allow functions to work with optional information.
Important Python Rule: Parameters with default values should follow parameters without default values in a function definition.
For example:
def greet(name, course="Python"):
print(name, course)
This is valid.
But the following definition is invalid:
def greet(course="Python", name):
print(name, course)
Python raises a syntax error because a required parameter cannot follow a default parameter.
6. Building Reusable Functions with Real-World Examples
Now that we understand function definitions, parameters, arguments and return statements, let's build practical Python programs.
Reusable code means writing a piece of code once and using it whenever needed.
Functions help us divide large programs into smaller, manageable parts.
Example 1: Building a Simple Calculator Using Functions
A calculator performs different mathematical operations.
We can create separate functions for addition, subtraction, multiplication and division.
Complete Python Code:
def add(a, b):
return a + b
def subtract(a, b):
return a - b
def multiply(a, b):
return a * b
def divide(a, b):
if b == 0:
return "Cannot divide by zero"
return a / b
print("Addition:", add(20, 10))
print("Subtraction:", subtract(20, 10))
print("Multiplication:", multiply(20, 10))
print("Division:", divide(20, 10))
Output:
Addition: 30 Subtraction: 10 Multiplication: 200 Division: 2.0
Understanding the Calculator Program
We created four separate functions.
add(): Adds two numbers.
subtract(): Subtracts the second number from the first number.
multiply(): Multiplies two numbers.
divide(): Divides the first number by the second number.
We also added a condition inside the division function:
if b == 0:
return "Cannot divide by zero"
This prevents division by zero.
Each function performs one specific task. This makes the calculator easier to understand, modify and maintain.
Example 2: Student Marks Calculator
Now let's create a function that calculates the percentage of a student using marks from three subjects.
Assume each subject has a maximum of 100 marks.
Complete Python Code:
def calculate_percentage(m1, m2, m3):
total = m1 + m2 + m3
percentage = (total / 300) * 100
return percentage
result = calculate_percentage(80, 90, 85)
print("Percentage:", result)
Output:
Percentage: 85.0
Understanding the Student Marks Calculator
The function accepts three parameters:
- m1: Marks in subject 1.
- m2: Marks in subject 2.
- m3: Marks in subject 3.
First, we calculate the total marks:
total = m1 + m2 + m3
Then, we calculate the percentage:
percentage = (total / 300) * 100
Finally, we return the percentage:
return percentage
This function can be reused for different students simply by passing different marks.
For example:
print(calculate_percentage(70, 80, 90)) print(calculate_percentage(85, 90, 95)) print(calculate_percentage(60, 75, 80))
Output:
80.0 90.0 71.66666666666667
This is a practical example of how functions help us avoid repeating calculations.
7. Best Practices for Writing Python Functions
Writing a function is not enough. We should also follow good programming practices.
Here are some important guidelines.
1. Use Meaningful Function Names
Choose names that clearly describe what the function does.
Good examples:
calculate_percentage() display_student() generate_report()
Avoid unclear names:
x() abc() function1()
2. Keep Functions Focused on One Task
A function should ideally perform one clearly defined task.
For example, create separate functions for calculating marks, displaying student details and generating results.
3. Avoid Unnecessary Code Repetition
If the same logic is required multiple times, consider creating a reusable function.
4. Use Parameters to Make Functions Flexible
Instead of hardcoding values, accept information through parameters.
def square(number):
return number * number
print(square(5))
print(square(10))
5. Use Return When You Need to Reuse a Result
Use return when another part of your program needs the calculated value.
6. Maintain Proper Indentation
Python uses indentation to identify the statements belonging to a function.
Example:
def greet():
print("Hello")
print("Welcome")
Incorrect indentation can cause errors.
7. Write Clear and Understandable Code
Use comments where necessary and avoid making functions unnecessarily complicated.
8. Real-World Applications of Python Functions
Functions are used in almost every area of Python development.
Let's understand some important applications.
1. Website Development
Functions help perform operations such as processing form data, validating information, calculating totals and managing application logic.
2. Django Applications
Django developers use functions to handle requests, process data and perform application operations.
For example, Django function-based views use Python functions to handle HTTP requests.
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to My Website")
Here, home() is a function-based Django view.
3. Data Science Projects
Functions help organize data cleaning, data transformation, calculations and analysis.
For example:
def calculate_average(numbers):
return sum(numbers) / len(numbers)
marks = [80, 90, 85, 75]
print("Average:", calculate_average(marks))
Output:
Average: 82.5
4. Automation Scripts
Functions can automate repetitive tasks such as file processing, data validation and report generation.
5. Software Development
Functions divide large applications into smaller components, making them easier to test and maintain.
6. API Development
Functions help process requests, validate inputs, execute business logic and prepare responses.
9. Common Mistakes Beginners Make While Using Functions
When learning Python functions, beginners often make some common mistakes.
Understanding these mistakes will help you write better programs.
Mistake 1: Forgetting to Call a Function
def greet():
print("Hello Students!")
This defines the function but does not execute it.
Correct approach:
def greet():
print("Hello Students!")
greet()
Mistake 2: Forgetting the Colon
Incorrect:
def greet()
print("Hello")
Correct:
def greet():
print("Hello")
Mistake 3: Incorrect Indentation
Incorrect:
def greet():
print("Hello")
Correct:
def greet():
print("Hello")
Mistake 4: Passing the Wrong Number of Arguments
def add(a, b):
return a + b
print(add(10))
This produces a TypeError because the function requires two arguments, but only one was provided.
Correct:
print(add(10, 20))
Mistake 5: Confusing print() with return
def add(a, b):
print(a + b)
result = add(10, 20)
print(result)
The final output includes None because the function does not return the calculated value.
If you need to reuse the result, use return.
Mistake 6: Incorrect Parameter Order
def student(name, age):
print(name, age)
student(23, "Aditya")
This is syntactically valid, but the values are assigned to the wrong parameters.
Correct:
student("Aditya", 23)
10. Frequently Asked Questions About Python Functions
Q1. What is a function in Python?
A function in Python is a reusable block of code that performs a specific task. It helps organize programs, reduce code repetition and make applications easier to maintain.
Q2. How do you define a function in Python?
Python uses the def keyword to define a function.
Example:
def greet():
print("Hello")
Q3. What is the difference between function definition and function calling?
Function definition means creating a function, while function calling means executing the function.
Q4. What are parameters in Python?
Parameters are variables written inside the parentheses of a function definition. They receive values when the function is called.
Q5. What are arguments in Python?
Arguments are the actual values passed to a function when calling it.
Q6. What is the difference between parameters and arguments?
Parameters are variables declared in a function definition, whereas arguments are the actual values supplied during a function call.
Q7. What is the return statement in Python?
The return statement sends a value from a function back to the caller. The returned value can be stored in a variable or used in another calculation.
Q8. What is the difference between print() and return?
print() displays information on the screen, whereas return sends a value back from a function.
Q9. What happens if a Python function does not have a return statement?
If a function finishes without returning a value explicitly, Python automatically returns None.
Q10. Can a Python function accept multiple parameters?
Yes. A function can accept multiple parameters.
Example:
def student(name, age, course):
print(name, age, course)
Q11. What are positional arguments?
Positional arguments are values assigned to parameters according to their positions in a function call.
Q12. What are keyword arguments?
Keyword arguments are passed using parameter names, allowing values to be assigned explicitly.
Q13. What are default arguments?
Default arguments are parameters that have predefined values. Python uses these values when the caller does not provide an alternative.
Q14. Can we call a function multiple times?
Yes. A function can be called multiple times throughout a program.
Q15. Why are Python functions important in Django?
Functions help organize application logic, process requests, perform calculations and manage reusable operations. Django also supports function-based views for handling HTTP requests.
Conclusion
Python functions are an essential part of Python programming. They help developers write clean, organized and reusable code.
In this lesson, we learned how to define and call functions, use parameters and arguments, return values, understand different types of arguments and build practical programs.
We also created a simple calculator and a student marks calculator using reusable functions.
Understanding these concepts will help you move towards more advanced Python programming, object-oriented programming, Django development, automation and data science.
The most important thing is to practise writing functions independently instead of only reading examples.
Keep practising, keep building and improve your Python programming skills step by step!
20 Python Functions Practice Questions
The following exercises are designed to help beginners apply the concepts covered in this lesson.
Try to solve these questions independently using Python.
Beginner Level
Question 1: Create a Welcome Function
Create a function named welcome() that displays:
Welcome to Python Programming!
Call the function three times.
Question 2: Create a Greeting Function
Create a function named greet() that accepts a student's name as a parameter and displays a personalized greeting.
Example:
Hello Aditya! Welcome to Python OJT.
Question 3: Addition Using Functions
Create a function named add() that accepts two numbers and returns their sum.
Test the function with 15 and 25.
Question 4: Square of a Number
Create a function named square() that accepts a number and returns its square.
Test it with 5, 10 and 15.
Question 5: Even or Odd Checker
Create a function named check_even_odd() that accepts a number and checks whether it is even or odd.
Hint: Use the modulo operator %.
Intermediate Level
Question 6: Student Details Function
Create a function named student_details() that accepts three parameters:
- Student name
- Age
- Course
Display all three details.
Question 7: Calculate Percentage
Create a function named calculate_percentage() that accepts marks in three subjects and calculates the percentage. Assume each subject has a maximum of 100 marks.
Question 8: Positional Arguments
Create a function named employee() that accepts employee name, employee ID and department as parameters. Call the function using positional arguments.
Question 9: Keyword Arguments
Create a function named product() that accepts product name, price and quantity. Call the function using keyword arguments in a different order from the function definition.
Question 10: Default Arguments
Create a function named course_details() that accepts a student name and a course name. Set the default course to "Python".
Call the function twice:
- Once without specifying the course.
- Once with "Django" as the course.
Practical Programming Challenges
Question 11: Simple Calculator
Create four separate functions:
- add()
- subtract()
- multiply()
- divide()
Each function should accept two numbers and return the calculated result. Handle division by zero.
Question 12: Maximum of Two Numbers
Create a function named find_max() that accepts two numbers and returns the greater number.
Question 13: Celsius to Fahrenheit Converter
Create a function named celsius_to_fahrenheit() that accepts temperature in Celsius and returns the Fahrenheit value.
Formula:
Fahrenheit = (Celsius × 9/5) + 32
Question 14: Simple Interest Calculator
Create a function named simple_interest() that accepts principal, rate and time.
Formula:
Simple Interest = (Principal × Rate × Time) / 100
Return the calculated interest.
Question 15: Factorial Using a Function
Create a function named factorial() that accepts a positive integer and calculates its factorial using a loop.
Example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Question 16: Count Vowels in a String
Create a function named count_vowels() that accepts a string and returns the total number of vowels.
Consider both uppercase and lowercase letters.
Question 17: Palindrome Checker
Create a function named is_palindrome() that accepts a string and checks whether it reads the same forward and backward.
Example:
madam
Expected result:
Palindrome
Question 18: Find the Average of a List
Create a function named calculate_average() that accepts a list of numbers and returns their average.
Also handle an empty list.
Question 19: Student Result Calculator
Create a function named calculate_result() that accepts marks in five subjects.
Requirements:
- Calculate total marks.
- Calculate percentage.
- Display the result.
- Return the percentage.
Assume each subject has a maximum of 100 marks.
Question 20: Build a Mini Student Management Utility
Create a Python program using multiple functions.
Your program should include:
- welcome() – Display a welcome message.
- student_details() – Accept and display student information.
- calculate_total() – Calculate total marks.
- calculate_percentage() – Calculate percentage.
- display_result() – Display the final student result.
Use appropriate parameters and return statements.
Final Practice Challenge: Try to complete all 20 questions without copying the examples. Write your code, execute it, check the output and fix any errors you encounter.



