Understanding Functions in Python - Guide for Beginners.

Nuwan Abeywickrama
6 min readNov 9, 2024

--

Welcome to the third article in our Python Learning Series! In this guide, I’ll cover everything you need to know about functions in Python. Functions are essential for writing clean, efficient, and reusable code. They allow us to break down complex problems into small parts, make code modular, and improve readability.

By the end of this article, you’ll be a giant in the function of Python. 😇🙂

  1. What is a Function?
  2. Defining a Function in Python.
  3. Types of functions (built-in, user-defined, lambda).
  4. Function arguments and parameters.
  5. Parameter Order in Function Definitions

1. What is a Function?

In Python, a function is a reusable block of code that performs a specific task. Functions allow us to have the below facilities.

  • Organize code logically.
  • Avoid redundant code by reusing function blocks.
  • Simplify code maintenance and debugging.

You’ve already encountered Python’s built-in functions, like print() and len(), but in this article, I’ll focus on creating user-defined functions.

2. Defining a Function in Python

To define a function, we use the def keyword, followed by the function name and parentheses ( ), which may include parameters. A function definition ends with a colon :, and the function body is indented.

Docstrings are used to document what a function does. They are enclosed in triple quotes """ """ and should describe the purpose, parameters, and return values (if any).

""" Docstring describing what the function does. """

def function_name(parameters):

# Code block to execute

return result # returns a value and may be optional.

3. Types of Functions in Python

Python has several types of functions, and understanding them helps build versatile programs.

a. Built-in Functions
b. User-Defined Functions
c. Lambda Functions

3.a. Built-in Functions

Built-in functions refer to those pre-defined functions that come along with the Python language (Not only Python, but other programming languages describe them like this).
They are intrinsic components of the language’s library, ready to be used without requiring additional installations. Python provides many built-in functions, like len(), sum(), and range(). These functions perform common tasks and are always available.

3.b. User-Defined Functions

User-defined functions are functions you create yourself to perform specific tasks.

def add_numbers(a, b):
"""
Returns the sum of two numbers.
"""
return a + b

Calling add_numbers(3, 5) will return 8.

3.c. Lambda Functions

A lambda function is a small, anonymous function defined with the lambda keyword. It is often used for short, simple operations that are only needed temporarily.

# Syntax of Lambda Functions

lambda arguments: expression
square = lambda x: x * x

print(square(5)) # Outputs: 25

Lambda functions are useful when you need a small function for a short period, like sorting or filtering lists.

4. Function Parameters and Arguments

In Python, parameters and arguments are foundational to understanding how functions work. Parameters are variables defined in the function definition, and Arguments are the actual values passed to the function when it is called.

Understanding the various types of parameters and arguments helps make functions versatile and allows them to handle different numbers and types of inputs, making your code flexible and reusable.

a. Positional Arguments.
b. Keyword Arguments.
c. Default Parameters.

d. Variable Length Arguments (*args and **kwargs)
e. Combining *args and **kwargs

4.a. Positional Arguments

Positional arguments are the simplest and most commonly used type of argument. They are passed to the function in the exact order defined in the function signature. The function maps each argument to its corresponding parameter based on the order.

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


introduce("Alice", 30) # OUTPUT : My name is Alice and I am 30 years old.
  • The function introduce takes two positional parameters, name and age.
  • When calling the function, "Alice" is assigned to name, and 30 is assigned to age based on their order.

📌 The order of arguments matters in positional arguments.
📌 If arguments are passed in the wrong order, it may cause unexpected results.

4.b. Keyword Arguments

With keyword arguments, you specify the parameter’s name while passing the argument, allowing you to pass them in any order. This makes the code more readable and reduces the chance of accidentally swapping arguments.

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

introduce(age=25, name="Alice") # OUTPUT: My name is Alice and I am 25 years old.
  • We call introduce using keyword arguments, specifying age first and name second.
  • Since each argument is labeled, the order in which arguments are passed does not matter.

📌 Keyword arguments improve code readability.
📌 They allow more flexibility in argument order.

4.c. Default Parameters

Default parameters allow you to define default values for parameters in the function signature. If an argument is not provided for a parameter with a default value, the function will use the default value.

def greet(name, greeting="Welcome"):
print(f"{greeting}, {name}!")

greet("Alex") # Uses default greeting | OUTPUT: Welcome, Alex!

greet("Alex", "Hi") # Uses provided greeting | OUTPUT: Hi, Alex!
  • The greeting parameter has a default value of "Welcome".
  • When greet("Alex") is called, greeting uses the default value, printing "Welcome, Alex!".
  • When callinggreet("Alex", "Hi"), "Hi" overrides the default greeting.

📌Default parameters must come after non-default parameters in the function signature.
📌Using default parameters can simplify function calls and reduce the number of arguments needed to pass.

4.d. Variable Length Arguments (*args and **kwargs)

Sometimes, you may not know in advance how many arguments a function needs to handle. Python provides two special symbols, * and **, to allow for variable-length arguments.

*args (Non-Keyword Variable Arguments)
This allows you to pass a variable number of positional arguments. The “args” in *args is not a keyword and can be given any name for it.

The *args syntax allows a function to accept any number of positional arguments, which are then collected into a tuple. In the function, theargs is treated as a tuple containing all the arguments passed to it.

def add_all(*numbers):
return sum(numbers)

print("Sum is ",add_all(1, 2, 3, 4)) # OUTPUT: Sum is 10

📌 Use *args when you want to allow the function to handle an arbitrary number of positional arguments.
📌 You can iterate over
args within the function, as it’s stored as a tuple.

**kwargs (Keyword Variable Arguments)
The **kwargs syntax allows a function to accept any number of keyword arguments, which are collected into a dictionary. The “kwargs” in **kwargs is not a keyword and can be given any name for it.

Inside the function, **kwargs is a dictionary where each key-value pair represents a keyword argument passed to the function.

def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")

print_info(name="Alex", age=30, job="Engineer")

# OUTPUT
# name: Alex
# age: 30
# job: Engineer

📌 Use **kwargs when you want to accept an arbitrary number of keyword arguments.
📌
**kwargs is ideal for handling dynamic parameters or optional settings.

4.e. Combining *args and **kwargs

You can use both *args and **kwargs in a function to handle a mix of positional and keyword arguments. When doing so, *args must appear before **kwargs in the parameter list.

def display_info(*args, **kwargs):
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)


display_info(1, 2, 3, name="Alice", age=30)

# OUTPUT
# Positional arguments: (1, 2, 3)
# Keyword arguments: {'name': 'Alice', 'age': 30}
  • The display_info function accepts both positional and keyword arguments.
  • *args collects all positional arguments in a tuple, while **kwargs collecting all keyword arguments in a dictionary.

📌 Using both *args and **kwargs provides maximum flexibility in handling function inputs.
📌 Be careful with the order of parameters,
*args must come before **kwargs.

5. Parameter Order in Function Definitions

When defining functions with multiple types of parameters, Python enforces a specific order which is mentioned below.

  1. Positional or keyword parameters
  2. Default parameters
  3. Variable positional arguments (*args)
  4. Keyword-only arguments
  5. Variable keyword arguments (**kwargs)
def full_example(a, b=2, *args, key1, key2="default", **kwargs):
print(f"a: {a}, b: {b}")
print("Positional arguments:", args)
print(f"Key1: {key1}, Key2: {key2}")
print("Additional keyword arguments:", kwargs)


full_example(1, 3, 5, 6, key1="value1", extra1="extra1", extra2="extra2")


# OUTPUT
# a: 1, b: 3
# Positional arguments: (5, 6)
# Key1: value1, Key2: default
# Additional keyword arguments: {'extra1': 'extra1', 'extra2': 'extra2'}
  • The function uses all types of parameters in the correct order.
  • The full_example function demonstrates how different parameter types are separated and stored when calling the function.

Understanding these parameter types is crucial for writing Python functions that can handle various inputs effectively and can help you create flexible, reusable code.

Stay tuned for the next article in this series, where I’ll cover OOP in Python. You will learn how to modularize code for better organization and reuse.

👉 Getting Started with Python: Understanding Syntax, Variables, and Data Types.
👉 Control Structures in Python — Conditional Statements (if) and Loops

You can follow me for upcoming articles. 🔔

The comment section is open for you to share special things, and new updates, and mention mistakes regarding this content. I’m also learning new things from your comments.
Sharing knowledge, learning new things, and helping others will help to develop a better world. Let’s share our knowledge to learn for everyone.🏆🏆🥇

Thank You. 🤝🤝

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Nuwan Abeywickrama
Nuwan Abeywickrama

Written by Nuwan Abeywickrama

Software QA Engineer | Tech & Science Enthusiast | Health Science Enthusiast

No responses yet

Write a response