Posted in

Understanding Functions in Python: Concept, Syntax, and Illustrative Examples

Functions in Python

In the programming world, there is a golden rule that every programmer must follow: Don’t Repeat Yourself (DRY). Instead of repeatedly writing the same code, programs should be divided into independent, reusable logical blocks. These blocks are functions.

Python, a language renowned for its simplicity and readability, treats functions as the “building blocks” of software. From small programs with just a few lines of code to complex applications spanning thousands of lines, functions are always present to make code clearer, more organized, and easier to manage.

In this article, we will cover everything from the basic concept to defining and using functions in Python, including syntax, parameters, return values, and variable scope. This will lay a solid foundation for progressing to more advanced techniques in the following sections.

1. What Is a Function in Python?

A function is a named block of code defined to perform a specific task. When needed, you can simply call the function by its name instead of rewriting the entire code block.

1.1. Benefits of Functions

  • Code reuse: write once, use in multiple places.
  • Reduce duplication: avoid copy–pasting the same logic.
  • Easy maintenance: updating the logic in a function automatically updates all calls.
  • Problem decomposition: helps make large programs easier to manage.

1.2. Comparison Example

Without using a function:

# In ra tổng của 3 cặp số
a, b = 5, 7
print(a + b)

x, y = 10, 15
print(x + y)

m, n = 100, 250
print(m + n)

With a function:

def sum_two_numbers(a, b):
    """Return the sum of two numbers"""
    return a + b

print(sum_two_numbers(5, 7))  # Output: 12

Clearly, code with functions is much more concise, readable, and easier to extend.

2. Syntax for Defining a Function in Python

In Python, a function is defined using the def keyword:

def function_name(parameters):
    """Docstring describing the function"""
    # Function body
    return value
  • function_name: the name of the function (usually lowercase, with underscores _ if multiple words).
  • parameters: a list of input parameters (optional).
  • return: the value returned by the function (optional).
  • docstring: a short string describing the purpose of the function.

Basic example

def greet(name):
    """Return a greeting message"""
    return f"Hello, {name}!"

print(greet("KienThucMo"))  # Output: Hello, KienThucMo!

3. Types of Functions in Python

3.1. Built-in Functions

Python has more than 60 built-in functions. Some common ones include:

  • print() – outputs data to the screen.
  • len() – gets the length of a string, list, tuple, etc.
  • type() – checks the data type.
  • sum() – calculates the sum of elements in an iterable.
  • range() – generates a sequence of numbers.

Example:

numbers = [1, 2, 3, 4]
print(len(numbers))   # 4
print(sum(numbers))   # 10
print(type(numbers))  # <class 'list'>

3.2. User-defined Functions

Programmers can define their own functions to handle custom logic.

def square(x):
    """Return the square of a number"""
    return x * x

print(square(5))  # 25

4. Parameters and Arguments

Python supports multiple ways to pass data into functions.

4.1. Positional arguments

Passed in order.

def introduce(name, age):
    print(f"My name is {name}, I am {age} years old.")

introduce("Tom", 20)  
# Output: My name is Tom, I am 20 years old.

4.2. Keyword arguments

Passed by parameter name, order does not matter.

introduce(age=22, name="Linda")  
# Output: My name is Linda, I am 22 years old.

4.3. Default arguments

Parameters with default values.

def greet(name, age=18):
    print(f"Hello {name}, you are {age} years old.")

greet("Alice")       # age = 18
greet("Bob", 25)     # age = 25

4.4. Arbitrary arguments

  • *args: accepts multiple arguments as a tuple.
  • **kwargs: accepts multiple arguments as a dictionary.
def sum_all(*args):
    """Return the sum of all arguments"""
    return sum(args)

print(sum_all(1, 2, 3, 4))  # 10


def show_info(**kwargs):
    """Print all key-value pairs"""
    for key, value in kwargs.items():
        print(key, ":", value)

show_info(name="Anna", age=20, city="New York")

5. Return Values

A function can return:

  • None if there is no return.
  • A single value.
  • Multiple values (as a tuple).

Example 1: No return

def say_hello():
    print("Hello!")

result = say_hello()
print(result)  # None

Example 2: Multiple return values

def calculate(a, b):
    sum_ = a + b
    diff = a - b
    return sum_, diff

x, y = calculate(10, 5)
print(x, y)  # 15 5

6. Scope and Lifetime of Variables

6.1. Local vs Global

  • Local variable: exists only within the function.
  • Global variable: declared outside a function and can be accessed anywhere.
x = 10  # global variable

def demo():
    x = 5  # local variable
    print(x)

demo()    # 5
print(x)  # 10

6.2. Global and Nonlocal

Use global or nonlocal to modify variables outside the function.

count = 0

def increase():
    global count
    count += 1

increase()
print(count)  # 1

7. Conclusion

Functions are one of the key pillars in Python, playing a central role in building programs with clear structure and easy maintainability. Mastering and effectively using functions provides numerous benefits, including:

  • Making code concise, readable, and easier to understand.
  • Reducing repetition, thereby improving reusability and maintainability.
  • Allowing the organization of programs into separate logical blocks, laying the foundation for extending and developing complex applications.

In this article, we have covered the following key topics:

  • The concept and syntax of defining functions in Python.
  • Types of functions: built-in functions and user-defined functions.
  • Methods for passing parameters (parameters/arguments).
  • The mechanism for returning values from functions.
  • Variable scope and lifetime.

A deep understanding and flexible application of these aspects will help you write more effective Python code while providing a solid foundation for advancing your programming skills.hơn, đồng thời tạo nền móng vững chắc để tiến xa trong quá trình học tập và phát triển kỹ năng lập trình.

8. References

  1. Python Software Foundation. (n.d.). The Python Tutorial: Defining Functions. Python.org. Retrieved September 27, 2025, from https://docs.python.org/3/tutorial/controlflow.html#defining-functions
  2. Sweigart, A. (2019). Automate the Boring Stuff with Python (2nd ed.). No Starch Press.
  3. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
  4. Matthes, E. (2019). Python Crash Course (2nd ed.). No Starch Press.
  5. Python for Professionals: Learning Python as a Second Language: https://www.kobo.com/us/en/ebook/python-for-professionals-3
  6. Python: Deeper Insights into Machine Learning: https://www.kobo.com/us/en/ebook/python-deeper-insights-into-machine-learning
  7. DataFusion Python Bindings in Practice: The Complete Guide for Developers and Engineers: https://www.kobo.com/us/en/ebook/datafusion-python-bindings-in-practice

Leave a Reply

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