Defining Functions
Package your code into reusable blocks with def — write once, use anywhere. The cornerstone of clean programming.
"If you write the same code twice, write a function instead. Functions are the single biggest leap from a beginner to a real programmer."
— ShurAIWhy Functions?
Imagine you need to greet a user at login, at checkout, and when they earn a badge. Without functions, you copy the same print statement three times. If the greeting changes, you must update three places. With a function — update once, fixed everywhere:
# Same code repeated in 3 places — fragile
print("Welcome, Riya! Good to see you.") # login
# ... 50 lines of code ...
print("Welcome, Riya! Good to see you.") # checkout
# ... 30 lines of code ...
print("Welcome, Riya! Good to see you.") # badge
# Define once
def greet(name):
print(f"Welcome, {name}! Good to see you.")
# Call anywhere, as many times as needed
greet("Riya") # login
greet("Riya") # checkout
greet("Riya") # badge
Anatomy of a Function
always
defyou choose this
input data
indented code
Defining and Calling
Defining a function does nothing by itself — it just saves the code for later. You run it by calling it with parentheses:
# DEFINE — creates the function (nothing runs yet)
def say_hello():
print("Hello from inside the function!")
print("This also runs when called.")
print("Before calling")
# CALL — now it actually runs
say_hello()
print("After calling")
Before calling
Hello from inside the function!
This also runs when called.
After calling
Functions with Parameters
Parameters are the inputs you give the function. Every time you call it, you can pass in different values:
def greet(name):
print(f"Hello, {name}! Welcome to ShurAI.")
greet("Riya") # Hello, Riya! Welcome to ShurAI.
greet("Arjun") # Hello, Arjun! Welcome to ShurAI.
greet("Sneha") # Hello, Sneha! Welcome to ShurAI.
Multiple Parameters
def introduce(name, age, city):
print(f"Hi! I am {name}, {age} years old, from {city}.")
introduce("Riya", 22, "Mumbai")
introduce("Vikram", 28, "Delhi")
# Hi! I am Riya, 22 years old, from Mumbai.
# Hi! I am Vikram, 28 years old, from Delhi.
Docstrings — Document Your Function
A docstring is a description written just inside the function using triple quotes. It is good habit and makes your code professional:
def calculate_bill(amount, tip_percent):
"""Calculate total bill including tip.
amount — the base bill in rupees
tip_percent — tip as a percentage (e.g. 10 for 10%)
"""
tip = amount * tip_percent / 100
total = amount + tip
print(f"Bill: Rs.{amount} Tip: Rs.{tip:.0f} Total: Rs.{total:.0f}")
calculate_bill(500, 10) # Bill: Rs.500 Tip: Rs.50 Total: Rs.550
calculate_bill(1200, 15) # Bill: Rs.1200 Tip: Rs.180 Total: Rs.1380
Real Example — Grade Reporter
def print_grade(name, score):
"""Print a student's result with grade and emoji."""
if score >= 90:
grade, emoji = "A", "🎉"
elif score >= 75:
grade, emoji = "B", "👍"
elif score >= 60:
grade, emoji = "C", "😊"
else:
grade, emoji = "F", "😢"
print(f"{emoji} {name:10} | Score: {score:3} | Grade: {grade}")
# Call for each student — same logic, no repetition
print_grade("Riya", 92)
print_grade("Arjun", 78)
print_grade("Sneha", 55)
print_grade("Vikram", 88)
🎉 Riya | Score: 92 | Grade: A
👍 Arjun | Score: 78 | Grade: B
😢 Sneha | Score: 55 | Grade: F
👍 Vikram | Score: 88 | Grade: B
Python reads your file from top to bottom. You must define a function before calling it. If you call greet() before the def greet(): line, Python raises a NameError.
"A function is a promise — give me this input and I will do this job. Every time. Reliably."
— ShurAI🧠 Quiz — Q1
What keyword is used to define a function in Python?
🧠 Quiz — Q2
When does the code inside a function actually run?
🧠 Quiz — Q3
What is the main benefit of using functions?
🧠 Quiz — Q4
What is a docstring?