⚙️ What is a Function in Python?
A function is a self-contained block of organized, reusable code designed to perform a specific task.
Functions help break down large programs into smaller, modular, and testable components. They accept input parameters, execute operations, and return computed results using the return keyword.
1. Basic Function Definition & Calling
Define a simple greeting function using the
def keyword and invoke it.
Python
# Defining a function
def greet_user(name):
print(f"Hello, {name}! Welcome to Nikita Infotech Python Training.")
# Calling the function
greet_user("Rahul")
greet_user("Priya")
Output:
Hello, Rahul! Welcome to Nikita Infotech Python Training.
Hello, Priya! Welcome to Nikita Infotech Python Training.
Real-Time Example 1: E-Commerce Bill Calculator with Parameters
Calculate order totals dynamically by passing item price and quantity as function parameters.
Python
def calculate_total_bill(price, quantity, tax_rate=0.05):
subtotal = price * quantity
total = subtotal + (subtotal * tax_rate)
return round(total, 2)
bill_amount = calculate_total_bill(1200, 3)
print("Final Calculated Bill: ₹", bill_amount)
Output:
Final Calculated Bill: ₹ 3780.0
Real-Time Example 2: Default Argument Values
Provide default parameter values so functions can be called with fewer arguments when standard values apply.
Python
def connect_server(host="localhost", port=8080):
return f"Connecting to server at {host}:{port}..."
print(connect_server()) # Uses default parameters
print(connect_server("192.168.1.50", 9000)) # Overrides default parameters
Output:
Connecting to server at localhost:8080...
Connecting to server at 192.168.1.50:9000...
Real-Time Example 3: Keyword Arguments
Pass arguments by explicitly naming parameters during the function call, regardless of order.
Python
def register_user(username, email, role):
print(f"Registered User -> Name: {username} | Email: {email} | Role: {role}")
# Calling using keyword arguments out of order
register_user(role="Administrator", username="admin_nikita", email="admin@infotech.com")
Output:
Registered User -> Name: admin_nikita | Email: admin@infotech.com | Role: Administrator
Real-Time Example 4: Arbitrary Arguments (*args)
Accept a variable number of positional arguments into a tuple using
*args for flexible aggregation.
Python
def sum_all_prices(*prices):
total = sum(prices)
return total
print("Cart Total 1:", sum_all_prices(450, 1200, 300))
print("Cart Total 2:", sum_all_prices(80, 150, 50, 200))
Output:
Cart Total 1: 1950
Cart Total 2: 480
Real-Time Example 5: Arbitrary Keyword Arguments (**kwargs)
Accept a variable number of keyword arguments packed into a dictionary using
**kwargs.
Python
def build_user_profile(username, **details):
print(f"Profile for: {username}")
for key, value in details.items():
print(f" - {key}: {value}")
build_user_profile("nikita_dev", role="Developer", experience=5, location="Pune")
Output:
Profile for: nikita_dev
- role: Developer
- experience: 5
- location: Pune
Real-Time Example 6: Lambda (Anonymous) Functions
Create small, one-line anonymous functions using the
lambda keyword for quick operations.
Python
# Lambda function to calculate square of a number
square = lambda x: x ** 2
# Lambda function to calculate GST on a price
calculate_gst = lambda price: price * 1.05
print("Square of 6:", square(6))
print("Price with 5% GST:", calculate_gst(1000))
Output:
Square of 6: 36
Price with 5% GST: 1050.0
Real-Time Example 7: Recursive Functions (Factorial Calculation)
Write functions that call themselves to solve problems like mathematical factorials or tree traversals.
Python
def compute_factorial(n):
if n == 0 or n == 1:
return 1
return n * compute_factorial(n - 1)
print("Factorial of 5 (5!):", compute_factorial(5))
Output:
Factorial of 5 (5!): 120
Real-Time Example 8: Returning Multiple Values
Return multiple calculated metrics packed as a tuple from a single function call.
Python
def analyze_scores(scores):
return max(scores), min(scores), sum(scores) / len(scores)
max_s, min_s, avg_s = analyze_scores([85, 90, 78, 92, 88])
print(f"Max: {max_s} | Min: {min_s} | Average: {avg_s:.2f}")
Output:
Max: 92 | Min: 78 | Average: 86.60
Real-Time Example 9: Scope Rules (Global vs Local Variables)
Understand how variables defined inside functions remain local unless modified using the
global keyword.
Python
app_status = "Online" # Global variable
def update_status():
global app_status
app_status = "Maintenance Mode"
print("Before function call:", app_status)
update_status()
print("After function call:", app_status)
Output:
Before function call: Online
After function call: Maintenance Mode