Python Functions Explained Simply

Write reusable code blocks that make your programs cleaner and more powerful
By Prakash Gangurde | BCA Student | Technical Content Creator | AI • Python • Linux
Part 2 of the Python for Absolute Beginners series
Introduction
Imagine you are writing a program that calculates a student's grade. You write the logic once. Then you realize you need to calculate the grade again in another part of the program. Do you copy and paste the same code?
No — you use a function.
A function is a block of code you write once and can use as many times as you need. It is one of the most important concepts in programming, and once you understand it, your code will become cleaner, shorter, and far easier to read.
In this article you will learn:
What a function is and why it matters
How to define and call a function in Python
The difference between parameters and arguments
How return values work
How to use default parameters
How to build a real project using everything you learn
Estimated reading time: 12–15 minutes This is Part 2 of the Python for Absolute Beginners series. If you have not read Part 1, start here: Python Basics for Absolute Beginners
What Is a Function?
A function is a named block of code that performs a specific task.
Think of it like a coffee machine. You press one button and it does everything — grinds the beans, heats the water, and pours the coffee. You do not need to know how it works internally. You just press the button and get the result.
In Python, a function works the same way:
You define it once (build the coffee machine)
You call it whenever you need it (press the button)
Without functions, your code looks like this — repetitive and hard to manage:
# Without functions — repeated code
student1_score = 85
if student1_score >= 90:
print("Grade: A")
elif student1_score >= 75:
print("Grade: B")
elif student1_score >= 60:
print("Grade: C")
else:
print("Grade: F")
student2_score = 72
if student2_score >= 90:
print("Grade: A")
elif student2_score >= 75:
print("Grade: B")
elif student2_score >= 60:
print("Grade: C")
else:
print("Grade: F")
With functions, the same logic becomes:
# With functions — clean and reusable
def get_grade(score):
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 60:
return "C"
else:
return "F"
print(get_grade(85)) # B
print(get_grade(72)) # C
print(get_grade(95)) # A
Same result. Half the code. Much easier to fix if something goes wrong.
Defining a Function — The def Keyword
To create a function in Python, you use the def keyword.
Here is the basic structure:
def function_name():
# code goes here
Let's write the simplest possible function:
def greet():
print("Hello! Welcome to Python.")
To run (call) the function, you write its name followed by parentheses:
greet()
Output:
Hello! Welcome to Python.
You can call it as many times as you want:
greet()
greet()
greet()
Output:
Hello! Welcome to Python.
Hello! Welcome to Python.
Hello! Welcome to Python.
The code inside greet() runs every time you call it — without you having to rewrite it.
Important: Indentation
Python uses indentation (spaces at the start of a line) to know what belongs inside a function. Every line inside the function must be indented by 4 spaces or one Tab.
def greet():
print("This is inside the function") # ✅ indented — belongs to greet()
print("This is outside the function") # ✅ no indent — runs separately
If you forget the indent, Python throws an IndentationError:
def greet():
print("Hello") # ❌ IndentationError — not indented
This is one of the most common mistakes for beginners. Always indent your function body.
Parameters and Arguments
Right now our greet() function always prints the same message. What if we want to greet different people by name?
This is where parameters come in.
A parameter is a variable you define inside the function parentheses — it acts as a placeholder for the value that will be passed in.
def greet(name): # name is a parameter
print(f"Hello, {name}! Welcome to Python.")
When you call the function, you pass the actual value — this is called an argument:
greet("Prakash") # "Prakash" is the argument
greet("Rahul")
greet("Priya")
Output:
Hello, Prakash! Welcome to Python.
Hello, Rahul! Welcome to Python.
Hello, Priya! Welcome to Python.
The difference between parameters and arguments
This confuses many beginners because tutorials use these words interchangeably. They are not the same:
def greet(name): # name = PARAMETER (the placeholder in the definition)
print(f"Hello, {name}!")
greet("Prakash") # "Prakash" = ARGUMENT (the actual value you pass)
Simple way to remember:
Parameter = the placeholder when you define the function
Argument = the actual value when you call the function
Multiple parameters
A function can take more than one parameter:
def introduce(name, age, course):
print(f"My name is {name}. I am {age} years old and studying {course}.")
introduce("Prakash", 21, "BCA")
introduce("Rahul", 20, "BSc CS")
Output:
My name is Prakash. I am 21 years old and studying BCA.
My name is Rahul. I am 20 years old and studying BSc CS.
Return Values
So far our functions print things to the screen. But what if you want a function to give you back a value that you can use later?
That is what the return keyword does.
def add(a, b):
return a + b
When you call this function, it gives back the result:
result = add(10, 5)
print(result) # 15
You can use the returned value directly in calculations:
total = add(10, 5) + add(3, 7)
print(total) # 25
print vs return — understanding the difference
This trips up almost every beginner:
# Using print inside function
def add_print(a, b):
print(a + b) # displays the result but gives nothing back
# Using return inside function
def add_return(a, b):
return a + b # gives the result back to use later
# The difference:
add_print(3, 4) # prints 7, but you can't store it
result = add_return(3, 4) # stores 7 in result — you can use it
print(result * 2) # 14
Rule of thumb:
Use
printwhen you just want to display somethingUse
returnwhen you want to use the result later in your program
Default Parameters
Sometimes you want a function to have a default value if no argument is passed.
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
Now you can call it two ways:
greet("Prakash") # uses default greeting
greet("Rahul", "Good morning") # uses custom greeting
Output:
Hello, Prakash!
Good morning, Rahul!
Default parameters must always come after regular parameters. This will cause an error:
def greet(greeting="Hello", name): # ❌ SyntaxError
print(f"{greeting}, {name}!")
This is correct:
def greet(name, greeting="Hello"): # ✅ default parameter at the end
print(f"{greeting}, {name}!")
A Note About input() and Types
Before we build our project, one important thing to remember from Part 1:
input() always returns a string — even if the user types a number.
age = input("Enter your age: ")
print(type(age)) # <class 'str'> — it's text, not a number
If you want to use it as a number, convert it:
age = int(input("Enter your age: ")) # converts to integer
score = float(input("Enter score: ")) # converts to decimal number
This matters in our project below because we will be working with scores.
Real Project — Student Report Card Generator
Let us build something genuinely useful. This program uses multiple functions to generate a complete student report card.
# Student Report Card Generator
# Written by Prakash Gangurde
def get_grade(score):
"""Returns the letter grade for a given score."""
if score >= 90:
return "A"
elif score >= 75:
return "B"
elif score >= 60:
return "C"
elif score >= 40:
return "D"
else:
return "F"
def calculate_percentage(total, max_marks):
"""Calculates percentage from total marks obtained."""
return round((total / max_marks) * 100, 2)
def get_remarks(percentage):
"""Returns remarks based on percentage."""
if percentage >= 90:
return "Outstanding"
elif percentage >= 75:
return "Excellent"
elif percentage >= 60:
return "Good"
elif percentage >= 40:
return "Needs Improvement"
else:
return "Please seek academic support"
def print_report(name, scores):
"""Prints a formatted report card for the student."""
subjects = ["Python", "Linux", "Web Dev", "Cybersecurity", "Database"]
total = sum(scores)
max_marks = len(subjects) * 100
percentage = calculate_percentage(total, max_marks)
remarks = get_remarks(percentage)
print()
print("=" * 40)
print(" STUDENT REPORT CARD")
print("=" * 40)
print(f"Name : {name}")
print("-" * 40)
for subject, score in zip(subjects, scores):
grade = get_grade(score)
print(f"{subject:<15} {score}/100 Grade: {grade}")
print("-" * 40)
print(f"Total : {total}/{max_marks}")
print(f"Percentage : {percentage}%")
print(f"Remarks : {remarks}")
print("=" * 40)
# --- Main Program ---
print("=== Student Report Card Generator ===")
print()
name = input("Enter student name: ")
print(f"\nEnter marks out of 100 for {name}:")
scores = []
subjects = ["Python", "Linux", "Web Dev", "Cybersecurity", "Database"]
for subject in subjects:
score = int(input(f" {subject}: "))
scores.append(score)
print_report(name, scores)
Sample output:
=== Student Report Card Generator ===
Enter student name: Prakash Gangurde
Enter marks out of 100 for Prakash Gangurde:
Python: 88
Linux: 92
Web Dev: 79
Cybersecurity: 95
Database: 83
========================================
STUDENT REPORT CARD
========================================
Name : Prakash Gangurde
----------------------------------------
Python 88/100 Grade: B
Linux 92/100 Grade: A
Web Dev 79/100 Grade: B
Cybersecurity 95/100 Grade: A
Database 83/100 Grade: B
----------------------------------------
Total : 437/500
Percentage : 87.4%
Remarks : Excellent
========================================
Notice what this project uses:
4 separate functions — each does one specific job
Parameters and return values
A loop to collect input
zip()to pair subjects with scoressum()to total the scoresf-strings for clean formatting
Each function is small, focused, and reusable. This is exactly how real programs are written.
Try It Yourself — Challenge
Before moving to the next article, try this challenge:
Write a function called
bmi_calculatorthat takes two parameters:weight(in kg) andheight(in metres). It should return the BMI value using the formula: BMI = weight / (height × height) Then write another function calledbmi_categorythat takes the BMI value and returns:
"Underweight" if BMI < 18.5
"Normal" if BMI is 18.5–24.9
"Overweight" if BMI is 25–29.9
"Obese" if BMI >= 30
This uses everything from this article: functions, parameters, return values, and conditions.
What to Learn Next
You now understand functions — one of the most important building blocks in programming. Here is what comes next:
| Topic | What it does |
|---|---|
| Lists and Tuples | Store collections of data |
| Loops | Repeat actions automatically |
| Dictionaries | Store key-value pairs |
| File Handling | Read and write files |
| Modules | Import and use existing code |
Each of these will be covered in the next articles in this series.
Summary — What You Learned Today
✅ What a function is and why it makes code better
✅ How to define a function using the
defkeyword✅ The difference between parameters and arguments
✅ How
returngives back values from a function✅ How default parameters work
✅ Why indentation matters inside functions
✅ How to build a real project using multiple functions together
All Code on GitHub
Every code example from this article is in my GitHub repository:
📌 GitHub: github.com/prakashgangurde-ux/python-basics
Let's Connect
If this article helped you, please clap on Medium — it helps other beginners find it.
Drop any question in the comments — I read and reply to every one.
LinkedIn: linkedin.com/in/prakashgangurde
GitHub: github.com/prakashgangurde-ux
Medium: medium.com/@gangurdeprakash
Next article: Lists in Python — Store and Manage Collections of Data
Written by Prakash Gangurde — BCA Student | Technical Content Creator | AI • Python • Linux

