Skip to content
C

Functions

Complete learning notes


1. Introduction

As programs grow, you'll find yourself writing the same block of code again and again — calculating an average, cleaning a piece of text, checking a condition. Functions let you write that logic once, give it a name, and reuse it anywhere. This is one of the most important habits for writing clean, professional Python code, and it's used constantly in ML work (custom preprocessing steps, evaluation metrics, helper utilities, etc.).


2. What is a Function?

Simple definition: A function is a named, reusable block of code that performs a specific task, which you can "call" (run) whenever you need it.

Technical explanation: A function is a self-contained unit of code defined using the def keyword, which may accept input values (parameters), perform operations, and optionally return an output value using return.


3. Why is it Important?

  • Avoids repeating the same code multiple times (a principle often called "Don't Repeat Yourself").
  • Makes programs easier to read, test, and debug, since each function handles one clear task.
  • ML libraries are built almost entirely out of functions — every time you call model.fit() or train_test_split(), you're calling someone else's function.

4. Prerequisites

You should be comfortable with variables, data types, and loops (Topic 2), and basic Python syntax (Topic 1).


5. Core Concepts

  1. Defining a function with def
  2. Parameters and arguments
  3. The return statement
  4. Default parameter values
  5. Local vs global scope
  6. Calling a function

6. Detailed Explanation

a) Defining a Function

You define a function using the def keyword, followed by a name, parentheses (which may contain parameters), and a colon. The function's code sits indented below.

b) Parameters and Arguments

A parameter is the placeholder name listed inside the function definition. An argument is the actual value you pass in when you call the function.

In simple words: parameters are like blank fields on a form; arguments are what you actually write in those fields.

c) The `return` Statement

return sends a value back to wherever the function was called from. A function without a return statement automatically returns None.

d) Default Parameter Values

You can give a parameter a default value, so if the caller doesn't supply that argument, the default is used instead.

e) Local vs Global Scope

A variable created inside a function only exists inside that function — this is called "local scope." Variables created outside any function have "global scope" and can be seen everywhere (though modifying them from inside a function requires special care).

f) Calling a Function

Once defined, you "call" (run) a function simply by writing its name followed by parentheses containing any required arguments.


7. How It Works

  1. Python reads the def block and stores the function's logic in memory — but does NOT run it yet.
  2. When you later "call" the function (e.g., greet("Riya")), Python jumps to the function's code.
  3. Any arguments you pass are assigned to the function's parameters.
  4. The function's code executes line by line.
  5. If a return statement is hit, the function immediately stops and sends that value back.
  6. Execution continues from where the function was called.

8. Real-World Example

Think of a function like a vending machine. You press a button (call the function) and pass in coins (arguments). Internally, the machine follows fixed steps (the function's code) and gives you back a snack (the return value). You don't need to know how the machine works internally — you just use it.


9. Technical Example

python
def add_numbers(a, b): result = a + b return result total = add_numbers(5, 3) print(total)

Here, a and b are parameters. When we call add_numbers(5, 3), the arguments 5 and 3 are assigned to a and b, and the function returns 8, which gets stored in total.


10. Python Example

python
# A simple function with no parameters def greet(): print("Welcome to the AI/ML course!") greet() # A function with parameters and a return value def add_numbers(a, b): return a + b result = add_numbers(10, 5) print("Sum:", result) # A function with a default parameter value def greet_student(name, course="AI/ML"): print(f"Hello {name}, enjoy learning {course}!") greet_student("Aarav") greet_student("Meera", "Data Science") # Demonstrating local vs global scope message = "I am global" def show_scope(): message = "I am local" print("Inside function:", message) show_scope() print("Outside function:", message) # A function used inside a loop def square(n): return n * n numbers = [1, 2, 3, 4] for num in numbers: print(f"Square of {num} is {square(num)}")

Expected Output:

text
Welcome to the AI/ML course! Sum: 15 Hello Aarav, enjoy learning AI/ML! Hello Meera, enjoy learning Data Science! Inside function: I am local Outside function: I am global Square of 1 is 1 Square of 2 is 4 Square of 3 is 9 Square of 4 is 16

11. Code Explanation

  • def greet(): defines a function that takes no input and simply prints a message when called.
  • def add_numbers(a, b): return a + b defines a function that accepts two parameters and sends their sum back to the caller.
  • def greet_student(name, course="AI/ML"): shows a default value — if course isn't provided, "AI/ML" is used automatically.
  • Inside show_scope(), creating a new message variable only affects that local copy — the global message outside remains unchanged, proving that local and global variables with the same name are completely separate.
  • square(num) is called repeatedly inside the loop, showing how functions combine naturally with loops to avoid repeating logic.

12. Advantages

  • Reduces code duplication and keeps programs organized.
  • Makes testing easier — you can test one function at a time.
  • Improves readability, since a well-named function documents itself.
  • Encourages reusability across different projects.

13. Limitations

  • Overusing very small, trivial functions can sometimes make code harder to follow (too much "jumping around").
  • Poor understanding of scope can lead to confusing bugs when the same variable name is used inside and outside a function.

14. Common Mistakes

  • Forgetting the return statement, then being surprised the function "returns nothing" (None).
  • Confusing print() (which just displays) with return (which actually sends a value back for further use).
  • Mixing up parameter order when calling a function with multiple arguments.
  • Assuming a variable changed inside a function will automatically update the outside (global) variable of the same name.

15. Best Practices

  • Give functions clear, descriptive names that describe what they do (e.g., calculate_average, not func1).
  • Keep each function focused on a single task.
  • Use default parameter values for optional settings to make functions flexible.
  • Add short comments explaining what a function does, especially for anything non-obvious.

16. Real-World Applications

  • Writing custom data-cleaning functions used across an entire ML pipeline.
  • Defining custom evaluation metric functions for model performance.
  • Wrapping repeated preprocessing steps (like scaling or encoding) into reusable functions.

17. Interview-Oriented Points

  • Be ready to explain the difference between a parameter and an argument.
  • Understand what happens when a function has no return statement (None is returned).
  • Know the difference between local and global scope, and how it can lead to subtle bugs.
  • Be able to explain why functions improve code maintainability.

18. Exam-Oriented Points

  • Functions are defined using def and can accept parameters and return values.
  • return sends a value back to the caller; without it, a function returns None.
  • Default parameter values are used only when the caller does not provide that argument.
  • Variables defined inside a function are local by default.

19. Comparison Table — print() vs return

Aspectprint()return
PurposeDisplays a value on screenSends a value back to the caller
Reusable in code?No — output is just text on screenYes — the value can be stored and reused
Stops the function?NoYes, execution stops right after return

20. Quick Revision

  • A function is a named, reusable block of code defined using def.
  • Parameters are placeholders; arguments are the actual values passed in.
  • return sends a result back; without it, a function returns None.
  • Default parameter values make arguments optional.
  • Variables created inside a function are local and don't affect variables of the same name outside it.

Mock Test

  • Functions — Quick Test

    A 10-question multiple-choice check on Functions.

    10 questions · 10 min · Easy
    Start Mock Test

Coding Problems

  • Problem 1: Simple Interest Calculator Function
    Easy · python
    Solve Problem
  • Problem 2: Even or Odd Checker Function
    Easy · python
    Solve Problem
  • Problem 3: Average of a List Function
    Easy · python
    Solve Problem
  • Problem 4: Greeting Function with Default Argument
    Easy · python
    Solve Problem