Python Functions: Notes for CBSE Class 12

Python Functions

1. Introduction to Python Functions

A function is a reusable block of code that only executes when it is called.

Core Characteristics

  • Non-Automatic Execution: Functions do not run simply because the program starts. They must be explicitly “called.”
  • Modularity: They break large, complex programs into smaller, manageable chunks.
  • Reusability: “Write once, use many times.” This reduces code redundancy.
  • Abstraction: You only need to know what a function does, not necessarily how it does it (e.g., you use print() without knowing the internal C code that handles the screen buffer).

2. The Three Types of Functions in Python

Python categorizes functions based on their source and accessibility.

TypeDefinitionExamples
Built-in FunctionsPre-defined functions always available in the Python interpreter.print(), input(), len(), type(), id()
Functions in ModulesFunctions stored in separate files (modules) that require an import statement.math.sqrt(), random.randint(), math.pow()
User-Defined Functions (UDF)Functions created by the programmer to perform specific logic using the def keyword.Addition(), Check_Even(), Calculate_Tax()

3. Syntax and Structure of User-Defined Functions

To create a function, you must follow a strict structural template. Pay close attention to the Flow of Execution, as this is a favorite 2-mark question in Board Exams.

The “Standard Addition” Template

The numbers in brackets [ ] indicate the order in which Python executes the lines.

[2] def addition():             # <--- FUNCTION HEADER (starts with 'def')
[3]     a = 10                  # \
[4]     b = 20                  #  |--- FUNCTION BODY (Indented block)
[5]     res = a + b             #  |
[6]     print("Sum is:", res)   # /

# --- The __main__ Section ---
[1] addition()                  # <--- FUNCTION CALL (Logic starts here)
[7] print("Execution Finished") # <--- Program ends here

Key Structural Rules:

  1. The def Keyword: Short for “define.” Do not use “define” or “function” keywords.
  2. Naming: Use Python Identifier rules (no spaces, cannot start with a digit).
  3. The Colon (:): Mandatory at the end of the header. It signals the start of the indentation block.
  4. The __main__ Section: This is the logical starting point of the program. Python skips the code inside def blocks until it sees a call in the __main__ section.

4. The Four Ways to Write a Function

Depending on how you handle data input and output, you can structure a function in four distinct ways. We will use the Addition logic to compare them.

1. No Argument, No Return Input and output both happen inside the function body.

def add():
    a, b = 10, 20
    print(a + b)
add()

2. With Argument, No Return Data is sent to the function (input), but the result is printed directly inside.

def add(a, b):
    print(a + b)
add(10, 20)

3. No Argument, With Return Input is taken inside, but the result is sent back to the caller for further use.

def add():
    a, b = 10, 20
    return a + b
res = add()
print(res)

4. With Argument, With Return The most professional way. Data is passed in, processed, and the result is returned.

def add(a, b):
    return a + b
print(add(10, 20))

5. Understanding Arguments and Parameters

TermAlso Known AsDefinition
Formal ParametersParametersVariables defined in the Function Header to receive values. (e.g., x in def func(x):)
Actual ArgumentsArgumentsThe actual values or variables passed during the function call. (e.g., 5 in func(5))

6. Advanced Argument Handling

Positional vs. Keyword (Named) Arguments

  • Positional: Arguments are matched to parameters by their order (1st to 1st, 2nd to 2nd).
  • Keyword: You specify the parameter name during the call. This allows you to change the order.
    • Example: def greet(name, age): ...
    • Call: greet(age=17, name="Aryan")

Default Arguments

You can assign “fallback” values to parameters. If the caller doesn’t provide a value, the default is used.

The “Right-to-Left” Rule: Once you use a default argument, all parameters to its right must also have default values.

  • def add(a, b=10, c=20): (Correct)
  • def add(a=5, b, c): (SyntaxError: non-default argument follows default argument)

7. Function Returns: Void vs. Non-Void

The Return Statement

The return keyword exits a function and sends data back. Python can return multiple values (e.g., return a, b), which are sent back as a Tuple.

The “None” Case (Void Functions)

If a function does not have a return statement, it is a Void (Non-Fruitful) function. If you try to assign its result to a variable, it will store None.

Board Question Example:

def demo():
    print("Hello") # Prints "Hello" to screen

x = demo()         # Function is called; "Hello" is printed.
print(x)           # Output: None (because demo() didn't return a value)

8. Scope of Variables: Local vs. Global

Variable “Scope” refers to the part of the program where a variable is accessible.

1. Local Scope (“The Gali Ka Gunda”)

A variable defined inside a function is a Local Variable. It is like a “neighborhood bully”—it has power only inside its own street (the function) and is invisible to the outside world.

def my_func():
    val = 50  # Local variable
    print(val)

my_func()
print(val) # ERROR: NameError: name 'val' is not defined.

2. Global Scope

Variables defined in the __main__ section or at the top level are Global. They are accessible throughout the entire program.

3. The global Keyword

By default, you can read a global variable inside a function, but you cannot modify it. To change a global variable’s value from inside a function, you must use the global keyword.

Comparison: | Without global (Creates a new Local) | With global (Modifies the Global) | | :— | :— | | a = 10 | a = 10 | | def update(): | def update(): | | a = 20 # New local 'a' | global a | | update() | a = 20 # Changes global 'a' | | print(a) # Output: 10 | update() | | | print(a) # Output: 20 |

4. The LEGB Rule (Priority Order)

When Python looks for a variable, it searches in this order:

  1. Local: Inside the current function.
  2. Enclosed: Inside a parent (outer) function.
  3. Global: At the top level of the script.
  4. Built-in: Reserved keywords in Python (like len).

9. Key Takeaways for Board Exams

  • The Sum Logic: To sum from 1 to N, your code must be range(1, n + 1). Using range(1, n) will exclude the number N.
  • Single-Element Tuples: In the type() identification questions, remember:
    • t = (20) is an Integer.
    • t = (20,) is a Tuple (the comma is the secret!).
  • The Colon Trap: Forgetting the colon (:) after the def header or if/else is the most common way to lose marks in “Rewrite the Code” questions.
  • Mutable Default Arguments: Never use a list as a default argument (like def func(l=[])). It persists across function calls!

Leave a Reply

Your email address will not be published. Required fields are marked *