Chapter 04b · Computer Science
63 blocks · bilingual

Programming In Python - 4.2 User Defined Function

LiveBilingual master notes · switch to नेपाली for the full glossary

Complete bilingual study notes for Programming In Python - 4.2 User Defined Function — every concept explained step by step, with definitions, formulas, and worked examples.

4.2 User-Defined Functions

What is a Function?

A function is a block of reusable code designed to perform a specific task. It helps break a large program into smaller, manageable parts, improving readability, reusability, and efficiency.

  • Code Reusability: Avoids repeating the same code by reusing a function multiple times.
  • Modularity: Breaks a large program into smaller, manageable parts.
  • Readability: Improves the structure and clarity of the code.
  • Easy Debugging: Makes it easier to find and fix errors.

Types of Functions

  • Library Functions (Built-in Functions): Predefined functions provided by Python, such as print(), input(), len(), sum(), max(), abs().
  • User-Defined Functions: Functions created by the programmer using the def keyword to perform a specific task.

Defining and Calling a Function

Defining a function means creating it using the def keyword, giving it a name, and writing the code that runs when it is called. Calling a function means executing it by writing its name followed by parentheses ().

Syntax: def function_name(parameters): """Optional docstring describing the function""" # function body (statements) return value # optional

Example: def greet(): print("Hello, welcome to Python!") greet() # Function call # Output: Hello, welcome to Python!

Diagram showing the flow of defining a function with def, calling it, executing its body, and (optionally) returning a value to the caller.

A function can also contain calculations. Example — simple interest: def simple_interest(): P = 1000 T = 2 R = 5 SI = (P * T * R) / 100 print("Simple Interest:", SI) simple_interest() # Output: Simple Interest: 100.0

Function Parameters — Types

A parameter is a variable listed inside the parentheses when a function is defined; it receives a value (called an argument) when the function is called.

i) Required / Positional Parameters

These must be supplied, in order, when the function is called.

Example: def add(a, b): print("Sum is:", a + b) add(5, 3) # Correct -> Sum is: 8 # add(5) # Error: missing one required argument

ii) Default Parameters

These take a default value automatically if no argument is passed for them.

Example: def greet(name="Guest"): print("Hello,", name) greet("Anita") # Hello, Anita greet() # Hello, Guest

iii) Keyword Parameters

Values are passed by explicitly naming the parameter; the order does not matter when parameter names are used.

Example: def student(name, grade): print("Name:", name) print("Grade:", grade) student(grade="A", name="Anita")

iv) Variable-Length Parameters (*args)

When the number of arguments is unknown, *args is used. It collects all extra arguments into a tuple.

Example: def add_numbers(*numbers): total = 0 for num in numbers: total += num print("Total is:", total) add_numbers(5, 10, 15) # Total is: 30 add_numbers(1, 2) # Total is: 3

Function Arguments — Types of Values

Arguments can be many different types of values passed into a function when it is called.

Example passing an expression: def double(value): print("Double is:", value * 2) double(5 + 3) # Double is: 16

Example passing another function's return value: def add(a, b): return a + b def display(result): print("Result is:", result) total = add(10, 20) display(total) # Result is: 30

Function Return Type

A function can send a result back to the part of the program that called it, using the return statement. When Python reaches return, it immediately exits the function and sends the value back to the caller. This returned value can be stored in a variable, used directly, or printed.

If a function has no return statement (or uses return with no value), Python automatically returns None. Such a function is informally called a void function.

  • A function can return a number.
  • A function can return a string.
  • A function can return a Boolean (True/False).
  • A function can return a tuple, list, or dictionary.
  • A function can return the result of another function's call.

Example — returning a number: def get_number(): return 50 result = get_number() print(result) # 50

Example — returning a Boolean: def is_adult(age): return age >= 18 print(is_adult(20)) # True

Example — returning a dictionary: def get_student_info(): student = {"name": "Nisha", "age": 14, "grade": "8th"} return student info = get_student_info() print("Student Details:", info)

Scope of Function in Python

Scope refers to the region of a program where a particular variable can be accessed or recognized. It defines the visibility and lifetime of a variable. Python mainly supports two types of scope.

Local Scope

  • Variables declared inside a function belong to the local scope.
  • These variables are only accessible within that function.
  • They are created when the function is called and destroyed once the function ends.

Example: def calculate_sum(): a = 7 b = 3 total = a + b print("Total inside function:", total) calculate_sum() # print(total) # Error: total is not defined outside the function

Global Scope

  • A global variable is declared outside of all functions.
  • It can be accessed and used anywhere in the program, including inside functions.
  • Global variables remain in memory until the program ends.

Example — reading a global variable inside a function: school_name = "Everest School" def display_school(): print("Inside function:", school_name) display_school() print("Outside function:", school_name)

To modify a global variable inside a function, the global keyword must be used: counter = 0 def increase_counter(): global counter counter = counter + 1 print("Inside function:", counter) increase_counter() print("Outside function:", counter) # Without 'global', Python would create a new local variable instead of changing the outer one.

Local Scope vs Global Scope

Diagram showing a global variable outside all functions and local variables inside separate functions, illustrating scope boundaries.

Passing Concept in Python Functions

Passing means sending a value (an argument) to a function through its parameters when the function is called. Python uses pass-by-object-reference: if a mutable object (like a list or dictionary) is passed, the function can modify the original object. If an immutable object (like a number, string, or tuple) is passed, the function receives a copy and cannot change the original value.

Example with an immutable type (int) — the original stays unchanged: def double_number(x): x = x * 2 print("Inside function:", x) num = 10 double_number(num) print("Outside function:", num) # Inside function: 20 # Outside function: 10

Example with a mutable type (list) — the original list is changed: def add_item(my_list): my_list.append(5) print("Inside function:", my_list) numbers = [1, 2, 3] add_item(numbers) print("Outside function:", numbers) # Inside function: [1, 2, 3, 5] # Outside function: [1, 2, 3, 5]

Note: strings and tuples are immutable, so trying to change them inside a function does not affect the original outside the function.

Review with Dry Run

A dry run is the process of manually tracing a program's execution — tracking variable values line by line — to predict its output without running it on a computer. This skill is very important for output-based questions in the SEE exam. A dry run table lists each key variable as a column and updates its value after every relevant statement, until the final output is reached.

Common Mistakes (4.2)

  • Forgetting to write the return statement when a function is supposed to send back a value.
  • Confusing print() inside a function (which only displays output) with return (which sends a value back to be used elsewhere).
  • Trying to change a global variable inside a function without using the global keyword.
  • Assuming that changing an immutable argument (like an int or string) inside a function changes it outside as well — it does not.
  • Placing parameters with default values before required parameters, which causes a syntax error.
  • Calling a function before it has been defined in the program.

SEE Exam Tips (4.2)

  • Clearly identify whether a question wants a function that prints a result or one that returns a result.
  • When tracing function calls, write down the parameter values received at each call before evaluating the function body.
  • Remember: lists and dictionaries can be changed inside a function; numbers, strings, and tuples cannot.
  • Use the global keyword whenever a function needs to modify a variable declared outside it.
  • Practice both writing functions and dry-running function calls, as both types of questions are common.

Quick Revision (4.2)

  • A function is defined with def and called using its name followed by parentheses.
  • Four types of parameters: positional (required), default, keyword, and variable-length (*args).
  • Arguments can be numbers, strings, Booleans, lists, tuples, dictionaries, variables, expressions, or another function's return value.
  • return sends a value back to the caller; a function with no return gives None.
  • Local variables exist only inside their function; global variables exist throughout the program.
  • Use the global keyword to modify a global variable inside a function.
  • Mutable objects (list, dict) can be changed inside a function; immutable objects (int, float, str, tuple) cannot.