ЁЯТ╗
тМия╕П
ЁЯЦ▒я╕П
ЁЯЦея╕П
ЁЯТ╛
тЖР Back to Dashboard
Font Size:

1. Introduction

A function is a named, reusable block of code that performs a specific task. Functions are the heart of organised programming because they allow a program to be broken into smaller, manageable pieces. Instead of writing the same code again and again, a function is written once and called whenever it is needed. This reduces repetition, makes programs shorter, easier to read, and easier to debug. Functions are the first step towards building large, maintainable software systems.

Python provides hundreds of built-in functions such as print(), len(), input(), and type(). In addition, users can define their own functions using the def keyword. User-defined functions give programmers the power to create custom operations that match their specific needs. A well-designed function does one job well and can be reused in many programs, saving time and effort.

In this chapter we will study the definition and calling of functions, parameters and arguments, the return statement, different categories of functions such as those with or without arguments and return values, and the important concept of scope of variables. We will also learn about local and global variables, and how arguments are passed to functions. By the end of the chapter, students will be able to write modular programs using functions.

2. Defining and Calling a Function

A function is defined using the def keyword followed by the function name, parentheses, and a colon. The function body is indented below the definition line.

def greet():
    print("Hello, Welcome to Python!")

To use the function, it must be called by its name followed by parentheses.

greet()

When this line executes, the code inside the function runs and prints the greeting message. A function must be defined before it is called in the program. Functions can be called as many times as needed, and each call executes the function body afresh.

General syntax

def function_name(parameters):
    statement(s)

The function name should be meaningful and follow Python naming rules, such as using lowercase letters and underscores.

3. Parameters and Arguments

Data can be passed into a function using parameters. A parameter is a variable listed inside the parentheses of the function definition, while an argument is the actual value passed to the function when it is called.

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

add(10, 5)      # Output: 15

Here a and b are parameters, and 10 and 5 are arguments. The values of the arguments are copied into the parameters when the function is called. A function can have any number of parameters, including zero. When a function has parameters, the number of arguments passed must match the number of parameters, unless default values are provided.

Default parameters

Parameters can be given default values, which are used when no argument is passed.

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

greet()            # Output: Hello Guest
greet("Riya")      # Output: Hello Riya

4. The Return Statement

A function can send a value back to the caller using the return statement. When return is executed, the function immediately stops and hands the value to the place where it was called. The returned value can be stored in a variable or used directly.

def square(n):
    return n * n

result = square(6)
print(result)      # Output: 36

A function without a return statement returns the special value None. The return statement can also be used without a value to exit a function early. Functions that return values are often called fruitful functions, while those that only perform actions are called void functions.

5. Categories of Functions

Based on arguments and return values, user-defined functions can be classified into four categories.

Example of the fourth category

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

print(add(10, 5))    # Output: 15

This classification is a favourite examination topic, so the four types must be memorised with examples.

6. Scope of Variables

The scope of a variable is the region of the program where the variable can be accessed. Python has two main scopes for beginners.

x = 10                # global variable

def display():
    y = 20            # local variable
    print(x, y)       # Output: 10 20

display()
print(x)              # Output: 10
# print(y) would give an error because y is local

If a local variable has the same name as a global variable, the local variable takes precedence inside the function. To modify a global variable inside a function, the global keyword must be used.

7. Passing Arguments: Positional and Keyword

In Python, arguments can be passed to a function in two ways.

def info(name, age):
    print(name, age)

info("Riya", 15)                # Positional arguments
info(age=15, name="Riya")       # Keyword arguments

Both styles can be mixed, but positional arguments must come before keyword arguments. Understanding this distinction helps in calling functions correctly.

8. Advantages of Using Functions

Functions also make testing easier, because each function can be tested separately before the whole program is assembled.

Quick Revision Tables

Category Arguments Return Value Example
Type 1 No No def show(): print("Hi")
Type 2 Yes No def add(a,b): print(a+b)
Type 3 No Yes def pi(): return 3.14
Type 4 Yes Yes def sq(n): return n*n
Term Meaning
def Keyword to define a function
Parameter Variable in the function definition
Argument Value passed when calling
return Sends a value back to the caller
None Value returned by functions without return
Local variable Accessible only inside the function
Global variable Accessible throughout the program

Mind Map

graph TD A["Python Functions"] --> B["Defining & Calling"] A --> C["Parameters & Arguments"] A --> D["Return Statement"] A --> E["Categories"] A --> F["Variable Scope"] B --> B1["def keyword, name, body"] C --> C1["Positional & Keyword"] C --> C2["Default parameters"] D --> D1["return sends value back"] E --> E1["With/without arguments"] E --> E2["With/without return value"] F --> F1["Local variables"] F --> F2["Global variables"]

Important Diagrams (SVG)

Diagram 1: How a Function Call Works

Main Program result = square(6) Function square(n) return n * n (6 * 6 = 36) call with 6 return 36 Execution Flow 1. Main program reaches the call square(6) 2. Control jumps to the function with n = 6 3. return sends 36 back; the result is stored in result Golden Rule: Arguments pass data into a function; return sends data back out.

Diagram 2: Local vs Global Variable Scope

Whole Program (Global Scope) Global variable: x = 10 Accessible everywhere in the program Function display() Local variable: y = 20 Accessible only inside the function print(y) outside fails Can read x here A function can read a global variable Golden Rule: Local variables exist only inside a function; global variables are visible everywhere.

Common Mistakes

  1. Forgetting to call the function. Defining a function does not run it; it must be called with its name and parentheses.
  2. Using return and print interchangeably. return sends a value to the caller, while print only displays it.
  3. Passing the wrong number of arguments for the defined parameters.
  4. Writing return on multiple lines incorrectly. return a + b must be a single expression statement.
  5. Trying to access a local variable outside its function, which causes a NameError.
  6. Modifying a global variable inside a function without declaring it with global.
  7. Naming a function the same as a built-in function, which overwrites the built-in behaviour.

Exam Tips

  1. Learn the four categories of functions with a one-line example of each, as this is a standard question.
  2. Practise writing a function with parameters and a return value, such as a function to calculate the area of a rectangle.
  3. Know the difference between print() and return clearly, since many students lose marks here.
  4. Remember that a function without a return statement returns None.
  5. Be able to explain local and global variables with a small example in descriptive answers.
  6. Always write correct indentation inside the function body, as Python functions fail with indentation errors.

Conclusion

Functions turn programming from writing long sequential code into building reusable, modular components. In this chapter we learned to define functions with the def keyword, pass data through parameters and arguments, and send results back using the return statement. We studied the four categories of user-defined functions based on arguments and return values, and the concept of variable scope, distinguishing between local and global variables. We also learned positional and keyword arguments. With functions, programs become shorter, more readable, and easier to debug. The next step in our Python journey is object-oriented programming, where functions and data are combined into classes and objects.