🐍
Syllabus / Python Programming / Phase 2: Loops, Conditional Statements, Functions (Days 6–10)
Beginner

Functions: def, Parameters, and Return Values

📂 Phase 2: Loops, Conditional Statements, Functions (Days 6–10) · Python Programming

A function is a reusable, named block of code that performs a specific task. Breaking a program into functions makes it modular, testable, and far easier to read than one long block of repeated logic — this is true in every language, and Python makes defining one especially lightweight.

Basic Function Syntax

def greet():
    print("Hello there!")

greet()   # calling the function
greet()   # call it again — runs the same code

Unlike Java, there is no access modifier, no return type declaration, and no curly braces — just the def keyword, a name, parentheses, and a colon, followed by an indented block.

Functions With Parameters

def greet(name):
    print(f"Hello, {name}!")

greet("Vishwas")   # Hello, Vishwas!
greet("Priya")     # Hello, Priya!

Returning a Value

def add(a, b):
    return a + b

result = add(5, 3)
print(result)   # 8

If a function has no explicit return statement, it automatically returns None — there is no concept of a "void" type in Python the way Java has void; it's simply the absence of a return value.

Parameters vs Arguments

Parameters are the variable names listed in the function definition. Arguments are the actual values passed in when the function is called.

def multiply(x, y):    # x, y = parameters
    return x * y

result = multiply(4, 5)   # 4, 5 = arguments

Returning Multiple Values

Python lets a function return more than one value at once, packed together as a tuple — something that requires far more boilerplate in many other languages.

def get_min_max(numbers):
    return min(numbers), max(numbers)

low, high = get_min_max([4, 9, 1, 7])
print(low, high)   # 1 9

Docstrings — Documenting What a Function Does

def calculate_area(length, width):
    """Returns the area of a rectangle given its length and width."""
    return length * width

print(calculate_area.__doc__)
# Returns the area of a rectangle given its length and width.

A docstring is the first statement inside a function, written in triple quotes — it can be read at runtime with help(function_name) or function_name.__doc__, and is the standard, expected way to document Python code.

Calling One Function From Another

def square(n):
    return n * n

def sum_of_squares(a, b):
    return square(a) + square(b)

print(sum_of_squares(3, 4))   # 9 + 16 = 25
Interview tip: Be ready to explain why functions matter beyond "less typing" — they enable code reuse, isolate logic for easier testing and debugging, and let you change an implementation in exactly one place instead of hunting through duplicated code everywhere it was copy-pasted.