Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • define a function using def
  • call functions with arguments
  • use return correctly
  • explain code reuse and modularity

Why functions matter

Functions help you:
  • reuse logic
  • reduce repetition
  • organize code
  • test smaller pieces independently

Basic syntax

def greet():
    print("Hello")

greet()

Function with arguments

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

greet("Asha")

Function with return value

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

result = add(3, 5)
print(result)
def show_sum(a, b):
    print(a + b)
This prints result but does not return it.
def get_sum(a, b):
    return a + b
This returns value for later use.

Scope idea (basic)

  • variables inside function are local by default
  • they are separate from variables outside

Exam hints and traps

  • function definition alone does not execute body
  • return ends function immediately
  • if no explicit return, function returns None

Quick practice

  1. Write function to square a number.
  2. Write function to greet a user by name.
  3. Predict:
def f():
    print("x")

print(f())

Answer key

  1. prints x, then prints None