Python Tutorial for Beginners #6: Functions and Self-Calling Code (Recursion) Explained

Raj PatelRaj Patel
9 min read

Remember yesterday when I promised you would learn to write reusable code like a pro? Well, grab your coffee because today we're diving into Functions & Recursion - the game-changers that will transform your messy, repetitive code into clean and professional code.

You are already familiar with the smart move of making computers do repetitive work with loops. But what happens when you find yourself writing the same block of code over and over again in different parts of your program? What if I told you there is a way to write code once and use it everywhere? That's exactly what we are covering today. If loops taught you automation, functions will teach you organization. And recursion? Recursion will blow your mind. By the end of this tutorial, you will be writing code that not only works but looks professional. You will stop copying and pasting the same code blocks. Instead, you will create reusable functions that make your programs cleaner, shorter, and eventually more powerful.

Let's unlock the secrets of Functions & Recursion!


What Are Functions?

Imagine you're building a program that needs to calculate the area of a rectangle in 5 different places. Without functions, you would write:

#Area 1
length1 = 10
width1 = 5
area1 = length1 * width1
print("Area: ",area1)

#Area 2
length2 = 50
width2 = 10
area2 = length2 * width2
print("Area: ",area2)


#Area 3
length3 = 12
width3 = 14
area3 = length3 * width3
print("Area: ",area3)

#Area 4
length1 = 15
width1 = 17
area4 = length4 * width4
print("Area: ",area4)


#Area 5
length1 = 25
width1 = 5
area5 = length5 * width5
print("Area: ",area5)

This is tiring isn’t it? Plus, what if you need to change how you calculate the area? You would have to update it in 5 different places. Here we use our superhero - functions. With functions, you write the code once and use it everywhere:

def calculate_area(length, width):
    area = length * width
    print("Area: ",area)
    return area

#Now you can use it anywhere.
calculate_area(10,5)
calculate_area(50,10)
calculate_area(12,14)
calculate_area(15,17)
calculate_area(25,5)

See how easy it gets, isn’t it ? You can call the function as many times you need it and you can easily incorporate a change, just in case if there is any and it would reflect everywhere. One function, infinite uses. Let's break down exactly how this works.

Think of functions as smart containers that hold pieces of code you want to use again and again. Instead of writing the same code multiple times, you write it once inside a function and just call it whenever you need it.

  • def keyword - This tells Python "Hey, I am about to create a function!"

  • function_name - Give your function a meaningful name (like calculate_area, greet_user, find_maximum).

  • (parameters) - These are the inputs your function needs to work with. Think of them as empty boxes that get filled when you call the function.

  • : - Don't forget the colon! It marks the start of your function's code block.

  • Indented code block - All the code that belongs to your function must be indented (4 spaces or 1 tab).

  • return statement - This sends a result back to whoever called the function. It's optional but very useful when you want to return values to the main program. You have three choices:

    • return value - Returns a specific value

    • return - Returns control without any value (returns None)

    • No return statement - Function automatically returns None when it ends

Let us build a function that greets the user:

def greet_person(name):
    #This function greets a person by name
    message = "Hello" + name +" Welcome to Python programming!"
    print(message)
    return 

# Now let's use it!
greet_person("IronWill")
greet_person("Rohit")
greet_person("Virat")

Always use Docstrings in the beginning of your function body. Docstrings are special comments that explain what your function does. They are written inside triple quotes and help other programmers understand your code.

How Functions Actually Work Behind the Scenes

Here is something crucial to understand: When you call a function, Python does not just copy-paste the code. Something much more interesting happens.

The Function Journey:

  1. Python is executing your main program line by line

  2. It hits a function call like greet_person(“IronWill”)

  3. Python STOPS the main program execution.

  4. Jumps into the function body and executes all the code inside

  5. When the function finishes (or hits a return), Python jumps back exactly where it left off in the main program

  6. Continues with the next line as if nothing happened.

Let us understand what exactly happens with the help of an example, this would make things more clear:

def greet_person(name):
    print("Inside function: Hello, " + name)
    return ("Greeting completed for " + name)

# Main program starts here
print("Program started")
print("About to call function")

result = greet_person("IronWill")  # Python jumps INTO the function

print("Back in main program.")
print("Function returned: ", result)
print("Program continues")

Output:

Program started
About to call function
Inside function: Hello, IronWill
Back in main program.
Function returned: Greeting completed for IronWill
Program continues.

Functions are like mini-programs within your program. When you call them, it's like pressing pause on your main movie, watching a short clip, then resuming exactly where you paused. This is why functions are so powerful as they can do their work and always return control back to your main program flow.

Function Parameters vs Arguments

Parameters are the variables in the function definition (the placeholders). Arguments are the actual values you pass when calling the function. Also, the order of passing the arguments is important, as they are interpreted in the same order as you pass them. Let us clear this with the help of an example:

def introduce_person(name, age, city):
    print("Hi, I am "+ name + "I am " + age + "years old and I live in " + city)

# Correct order - works perfectly
introduce_person("Rohit", 40, "Mumbai")
# Output: Hi, I am Rohit. I am 40 years old and I live in Mumbai.

# Wrong order - creates confusion
introduce_person("Mumbai", "Raj", 25)
# Output: Hi, I am Mumbai. I am Rohit years old and I live in 40.

Caught the Problem? Python assigns arguments to parameters positionally - first argument goes to first parameter, second to second, and so on. This is called Positional Arguments because position matters. Always double-check the order of your arguments.

Keyword Arguments

Keyword Arguments are a way to pass arguments to a function by explicitly naming which parameter each argument should go to, instead of relying on position/order.

def create_profile(name, age, city, profession):
    return (name+ ", " + age + " years old, " + profession + " from " +city)

# Using keyword arguments where order does not matter
profile = create_profile(city="Mumbai", name="Priya", profession="Teacher", age=30)
print(profile)  # Priya, 30 years old, Teacher from Mumbai

# You can even mix and match!
profile = create_profile("Rahul", profession="Doctor", city="Pune", age=35)
print(profile) #Rahul, 35 years old, Doctor from Pune

Keyword Arguments provide order independence, meaning you can pass the arguments in any order. It makes your code more readable because you know exactly what each value represents. You can even skip optional parameters.


Recursion

Ready for your brain to do a little flip? We are about to explore one of programming's most elegant and powerful concepts: Recursion - where functions call themselves to solve problems. Recursion is when a function calls itself to solve a smaller version of the same problem. It is like looking into two mirrors facing each other where you see infinite reflections, each one smaller than the last. It comes from the idea that instead of solving a big problem directly, break it into smaller and identical problems until you reach something so simple that you can solve it immediately.

Imagine this scenario: You have a stack of 10 books on your desk, and you need to find your Python Programming book. It could be anywhere in the stack.

The Recursive Approach:

  1. Look at the top book

  2. Is it the book you want?

    • YES → Found it. Stop searching.

    • NO → Remove this book and repeat the same process with the remaining stack.

Every recursive function needs two essential parts:

1. Base Case

The condition where the function stops calling itself. Without this, your function would call itself forever and would cause stack overflow. You can think of base case as a stopping sign.

2. Recursive Case

This is where the magic happens. The function calls itself, but with a simpler version of the problem. Each call gets us closer to the base case until we can finally solve it.

Let us look at recursion with a simple example:

def count_down(number): # Function definition
    # Base case: When we reach 0, stop
    if number == 0:
        print("Done!")
        return

    # Print current number
    print(number)

    # Recursive case: Decrease the count down by 1
    count_down(number - 1)

count_down(5) #Function call

Output:

5
4
3
2
1
Done!

Let us understand this better with the help of a diagram

That's it**!** The function keeps calling itself with a smaller number until it reaches 0. No complex logic, no confusing data structures, just a simple countdown.

Instead of writing a loop, you let the function call itself. Each call handles one number, then passes the rest to the next call.

Let us calculate factorial of a number with recursion:

def factorial(n):
    # Base case
    if n <= 1:
        return 1
    # Recursive case
    return n * factorial(n - 1)

print(factorial(5))  # 5 * 4 * 3 * 2 * 1 = 120
# Output: 120

See, so short and simple!

  • Use recursion when you have tree-like structures (family trees, file systems) , Divide-and-conquer problems and when the problem naturally breaks into smaller similar problems. Recursion is powerful but can be memory-intensive

  • Use loops when you have simple counting or iterations, or when the problem does not naturally break down. Loops can be used when you need better performance.

Congratulations! You have just mastered Functions and Recursion - two concepts that separate beginner programmers from professionals. You now write reusable code with functions instead of repeating yourself, understand how to pass data with parameters and arguments, and you've witnessed the mind-bending magic of recursion where functions call themselves to solve complex problems. Your code is no longer just working , it is organized, elegant, and professional.

Time to practice and solidify these concepts. Before our next tutorial on Strings (where you will master text manipulation like splitting, joining, and formatting), challenge yourself: refactor any previous code by converting repetitive parts into functions, write a recursive function to calculate the sum of numbers from 1 to N, and build a simple calculator using functions for each operation. The more you practice functions and recursion today, the more natural they will become tomorrow.

Ready to become a string manipulation master? Stay tuned!

Enjoyed today’s blog? Don’t forget to like, share it with your friends, and leave your valuable feedback – it really helps! Your support keeps the content coming.

Keep practicing and Happy Coding! 🚀

0
Subscribe to my newsletter

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

Written by

Raj Patel
Raj Patel

Hey there! I'm Raj Patel, a passionate learner and tech enthusiast currently diving deep into Data Science, AI, and Web Development. I enjoy turning complex problems into simple, intuitive solutions—whether it's building real-world ML projects like crop disease detection for farmers or creating efficient web platforms for everyday use. I’m currently sharpening my skills in Python, Machine Learning , Javascript and love sharing what I learn through blogs and open-source contributions. If you're into AI, clean code, or building impactful tech—let’s connect!