🧠 Python Functions – Write Once, Use Many Times | TechTown.in

In programming, repetition isn’t smart — it’s boring. That’s where functions come in! A Python function lets you wrap a block of code under a name and reuse it whenever you want.

Whether you’re calculating totals, processing user input, or building full-fledged applications, mastering Python functions helps you write cleaner, smarter, and DRY (Don’t Repeat Yourself) code.

Let’s dive in and simplify functions once and for all.


🧾 What is a Function in Python?

A function is a named block of code that runs only when called.

def greet():
    print("Hello, welcome to TechTown!")

✅ This code defines a function named greet(). It doesn’t run until you call it:

greet()

🧩 Why Use Functions?

  • ✅ Reuse code
  • ✅ Make code more readable
  • ✅ Organize logic into chunks
  • ✅ Simplify debugging

🔧 How to Define a Function

def function_name():
    # block of code
    print("I am a function.")

Call it like this:

function_name()

🧮 Functions with Parameters

You can pass data to functions using parameters:

def greet(name):
    print("Hello, " + name)

greet("Tanmay")

🎯 Output: Hello, Tanmay


➕ Multiple Parameters

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

add(5, 3)  # Output: 8

🔁 Return Values from Functions

Use return to send a result back from the function.

def square(x):
    return x * x

result = square(4)
print(result)  # Output: 16

🎯 Function Recap

ConceptExample
Define a functiondef my_func():
Call a functionmy_func()
Function with paramdef greet(name):
Return valuereturn result

🧠 Real-Life Use Case

Imagine you’re building a billing app. You could write a function like this:

def calculate_total(price, tax=0.18):
    return price + (price * tax)

print(calculate_total(100))  # Output: 118.0

✅ Easy to test, reuse, and modify!


🔄 Function Best Practices

  • Use meaningful names for functions and parameters
  • Keep functions short and focused
  • Add default values when needed (tax=0.18)
  • Avoid using global variables inside functions
  • Add docstrings to explain purpose

🏁 Final Thoughts

Functions are the building blocks of every Python program. Once you understand how to define, call, and return values from functions, you’ll write modular and powerful code that scales.

So next time you repeat something, turn it into a function!


📘 Learn more Python essentials at TechTown.in