Functions in Python: A Beginner’s Guide to Writing Reusable Code

1. INTRODUCTION

Functions are used when we want to group a block of code and reuse it multiple times. Instead of writing the same code again and again, we can just create a function and call it whenever needed.

👉 Example from real life: If you use a calculator, you don’t need to build “add” or “subtract” again and again. The calculator already has those functions. Similarly, in Python, we can define functions once and use them whenever we need.


2. CREATING A FUNCTION

Syntax –

def function_name():
    # code block

Example:

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

greet()

Output –

Hello, welcome to Python!

So here:

  • def → keyword used to define a function.

  • greet() → function name.

  • () → parentheses where arguments can be passed (if required).

  • Function is called by using its name followed by ().


3. FUNCTION ARGUMENTS

Arguments are values that we pass to a function so that it can work with them.

Let’s see the different types:

(a) Positional Arguments

These are the most common. The order matters.

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

add(5, 3)

Output –

8

Here a=5 and b=3. The function adds them.


(b) Default Arguments

We can give a default value. If we don’t pass anything, the default is used.

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

greet()
greet("Prajitha")

Output –

Hello, Guest
Hello, Prajitha

(c) Keyword Arguments

We can pass arguments in any order by using keywords.

def student(name, age):
    print("Name:", name, "Age:", age)

student(age=20, name="John")

Output –

Name: John Age: 20

(d) Arbitrary Arguments

Sometimes we don’t know how many arguments will be passed.

  1. *args → for multiple positional arguments
def fruits(*args):
    for fruit in args:
        print(fruit)

fruits("Apple", "Mango", "Banana")

Output –

Apple
Mango
Banana

Here, args behaves like a tuple.

  1. **kwargs → for multiple keyword arguments
def student_details(**kwargs):
    for key, value in kwargs.items():
        print(key, ":", value)

student_details(name="Ananya", age=22, course="AI")

Output –

name : Ananya
age : 22
course : AI

Here, kwargs behaves like a dictionary.


4. RETURN STATEMENT

Functions can also return values back.

def multiply(a, b):
    return a * b

result = multiply(4, 5)
print(result)

Outpu –

20

👉 Difference:

  • print() → only displays.

  • return → sends the result back, which we can use later.


5. VARIABLE SCOPE

  • Local Variable → created inside a function (used only inside).

  • Global Variable → created outside any function (used everywhere).

x = 10  # global

def show():
    y = 5  # local
    print("Inside:", x + y)

show()
print("Outside:", x)

6. NESTED FUNCTIONS

A function inside another function.

def outer():
    def inner():
        print("This is inner function")
    inner()

outer()

7. RECURSION

When a function calls itself.

Example – Factorial

def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n-1)

print(factorial(5))

Output –

120

8. LAMBDA FUNCTIONS

Anonymous (nameless) functions. Usually one-liners.

square = lambda x: x * x
print(square(6))

Output –

36

Also useful with map() and filter().

nums = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, nums))
print(squared)

Output –

[1, 4, 9, 16]

9. PRACTICE QUESTIONS

Try solving these 👇

  1. Write a function to calculate the area of a circle (take radius as input).

  2. Create a function that returns the maximum number in a list.

  3. Write a recursive function for Fibonacci numbers.

  4. Write a function that checks if a number is prime.

  5. Write a function that checks if a string is a palindrome.

  6. Create a lambda function to find the cube of a number.

  7. Write a function that counts vowels in a string.

  8. Use *args to find the sum of any number of numbers.


10. CONCLUSION

Functions are used to write clean, reusable and modular code.

  • Positional, default, keyword, args and *kwargs make functions flexible.

  • Return statement is used to send results back.

  • Scope decides where variables can be used.

  • Advanced concepts like recursion and lambda make functions even more powerful.

👉 Mastering functions is very important because every Python program is built on top of them.


11. BONUS PRACTICE

🔹 Calculator Function → Create a function that performs add, subtract, multiply, divide.
🔹 ATM Function → A function with deposit, withdraw, and balance check.
🔹 Student Grade Function → Function to calculate grade from marks.

0
Subscribe to my newsletter

Read articles from Tammana Prajitha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Tammana Prajitha
Tammana Prajitha