From Chaos to Clarity: Mastering Functions in Python
Breaking down Python functions with simple examples for beginners.
When I first started learning Python, my code was very repetitive. If I wanted to perform the same task multiple times, I had to write the same lines of code again and again. At first it worked, but as my programs grew longer, my code started looking messy and harder to manage.
That’s when I discovered functions. It felt like a game-changer. Instead of rewriting the same logic repeatedly, I could put it inside a function and reuse it whenever I needed. My code suddenly became cleaner, shorter, and easier to understand.
Learning functions also helped me think more like a programmer. I started breaking big problems into smaller pieces and solving them step by step. That shift in thinking made coding much more organized and enjoyable.
Since then, functions have become one of the most important tools in my programming journey.
Introduction to functions:
As Beginners we write the same code multiple times, which makes programs longer and harder to manage. Functions solve this problem by allowing developers to group reusable code into a single block tha can be used whenever needed. Learning functions is important because they make programs in Python more organized, readable, and easier to maintain.
What is a function ….??
A function is a reusable block of code that performs a specific task. It helps avoid repeating the same code and makes programs more organized in python.
Real-Life example for Functions.
Think of a function like a coffee machine ☕. You press button, and the machine performs a specific task — making coffee. Every time you press the button, it repeats the same process.
def greet(name):
print("Hello", name)
greet("Santhosh")Syntax of a function::
A Python function is defined using “def” , takes inputs through parameters, runs code inside its body, and optionally returns a result using “return”.
Creating your First Function:::
Creating a function in Python is simple. A function allows you to group a set of instructions together and reuse them whenever needed.
Basic Syntax:
def function_name():
# code to runExample: Your First Function:
def greet():
print("Hello!")
print("Welcome to Python.")Calling the Function:
After defining the function, you must call it to run the code inside it.
greet()Output:
Hello!
Welcome to Python.- def → tells Python you are creating a function.
- greet → the name of the function.
- ( ) → parentheses used for parameters (empty here).
- : → indicates the start of the function block.
- Indentation→ the indented code belongs to the function.
Arguments:
When I first started using functions, I thought they were perfect. I could reuse code and keep things organized. But soon, I ran into a small problem. Every time I called a function, it did the same exact thing.
For example, I created a function to greet a user:
def greet():
print("Hello Santhosh")It worked… but only for one person.
What if I wanted to greet different people?
I realized I would have to create multiple functions like greet1(), greet2(), or keep changing the code every time. That completely defeated the purpose of using functions.
That’s when I discovered arguments.
Arguments made functions flexible. Instead of hardcoding values, I could pass data into the function and let it work dynamically.
def greet(name):
print("Hello", name)
greet("Santhosh")
greet("Ravi")
greet("Anu")Now, the same function could greet anyone!
That moment changed how I looked at functions. I understood that:
- Functions define what to do
- Arguments decide with what data to do it
It felt like upgrading from a fixed machine to a smart one that adapts based on input.
Since then, arguments have become essential in writing dynamic and reusable programs. They allow functions to handle different situations without rewriting code, making programming more efficient and powerful.
Types of Arguments:
1.Default Parameters
- Assign a default value to a parameter
- Used if no argument is passed
def greet(name="Guest"):
print(name)2. Keyword Arguments:
- Pass values using parameter names
- Order doesn’t matter
def student(name, age):
print(name, age)
student(age=20, name="Santhosh")Parameters vs Arguments
- Parameters → variables in function definition
- Arguments → actual values passed to the function
def greet(name): # parameter
print(name)
greet("Santhosh") # argumentInstead of writing the same code multiple times, you can define it once in a function and reuse it whenever needed.
Functions with Return Values:
The return statement is used to send a result back from a function to the place where the function was called. Instead of just printing a value, return gives the result so it can be stored in a variable or used later in the program in python.
def add(a, b):
return a + b
result = add(3, 5)
print(result)Output::
8Return vs Print
- print() → displays output on screen
- return()→ sends value back to the caller
def add(a, b):
return a + bTypes of Functions::
- Built-in Functions
These are functions that are already available in Python. You can use them directly without creating them.
Examples: print( ), len( ), type( )
2. User-defined Functions:
These are functions created by programmers to perform specific tasks in their programs.
Example:
def greet(name):
print("Hello", name)3. Lambda Functions:
These are small, anonymous (nameless) functions used for short operations. They are usually written in a single line.
Example:
add = lambda a, b: a + b
print(add(3, 4))syntax of lambda functions:
For the syntax:
a = lambda x: x**2One-word explanation of each part:
- a → Variable
- lambda → Keyword
- x → Argument
- : → Separator
- x**2 → Expression
This is a lambda function in Python that returns the square of x .
Get Santhosh kumar Puppala’s stories in your inbox
Join Medium for free to get updates from this writer.
Use Cases of Lambda Functions
Let’s see some of the practical uses of the Python lambda function.
1. Using with Condition Checking
A lambda function can use conditional expressions (if-else) to return different results based on a condition.
check = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"print(check(5))print(check(-3))print(check(0))Output
Positive
Negative
ZeroExplanation:
- The lambda function takes x as input.
- It uses nested if-else statements to return “Positive,” “Negative,” or “Zero.”
Below example checks divisibility by 2 and returns “Even” or “Odd” accordingly.
check = lambda x: "Even" if x % 2 == 0 else "Oddprint(check(4)print(check(7)Output
Even
OddExplanation:
- The lambda checks if a number is divisible by 2 (x % 2 == 0).
- Returns “Even” for true and “Odd” otherwise.
2. Using with List Comprehension
Lambda functions can be combined with list comprehension to apply the same operation to multiple values in a compact way.
func = [lambda arg=x: arg * 10 for x in range(1, 5)]for i in func:print(i())Output
10
20
30
40Explanation:
- lambda function multiplies each element by 10.
- list comprehension iterates through li and applies the lambda to each element.
3. Using for Returning Multiple Results
Although a lambda can contain only one expression, it can still return multiple results by combining them into a tuple.
calc = lambda x, y: (x + y, x * y)res = calc(3, 4)print(res)Output
(7, 12)Explanation: lambda function performs both addition and multiplication and returns a tuple with both results.
4. Using with filter()
filter() function uses a lambda expression to select elements from a list that satisfy a given condition, such as keeping only even numbers.
c = [1, 2, 3, 4, 5, 6]even = filter(lambda x: x % 2 == 0, c)print(list(even))Output
[2, 4, 6]Explanation:
- The lambda function checks if a number is even (x % 2 == 0).
- filter() applies this condition to each element in nums.
5. Using with map()
map() function applies a lambda expression to each element of a list and returns a new list with the transformed values.
a = [1, 2, 3, 4]double = map(lambda x: x * 2, a)print(list(double))Output
[2, 4, 6, 8]Explanation:
- The lambda function doubles each number.
- map() iterates through a and applies the transformation.
6. Using with reduce()
reduce() function repeatedly applies a lambda expression to elements of a list to combine them into a single result.
from functools import reducea = [1, 2, 3, 4]mul = reduce(lambda x, y: x * y, a)print(mul)Output
24Explanation:
- The lambda multiplies two numbers at a time.
- reduce() applies this operation across the list.
Best Practices::
- Use clear names — Function names should describe what they do (e.g., calculate_total() ).
- Keep functions small — Each function should perform one specific task.
- Use parameters — Pass data as arguments instead of using many global variables.
- Return values when needed — Use return to send results back instead of only printing.
- Write readable code — Follow proper indentation and simple logic for easier understanding.
- Add comments if needed — Briefly explain complex logic inside the function.
These practices help make your code cleaner, reusable, and easier to maintain.
Conclusion::
Functions are an important concept in Python that allow programmers to organize code into reusable blocks. They help reduce repetition and make programs easier to read and maintain.
By using functions, developers can write cleaner and more structured code while solving problems more efficiently.
As a beginner, the best way to understand functions is through regular practice. Try creating your own functions and experimenting with different examples to strengthen your programming skills.






