Posted on 6/18/2025 5:41:09 PM by Admin

Building Reusable Code in Python with Functions

In our journey so far, we have learned the fundamental building blocks of programming in Python. We've covered variables, data types, operators, control flow with conditionals and loops, essential data structures, and error handling. You now know how to store data, make your program make decisions, repetitively run a block of code, and organize the blocks of data. But, as your programs grow, you will find yourself writing the same or similar blocks of code again and again. This causes redundant code and leads to inefficient programs that are harder to read and maintain.

This is where the need for the functions arises. Functions, in their simplest form, are the named blocks of code that perform a specific task whenever called. They are crucial for writing clean, more organized, highly efficient, and maintainable code. They implement the DRY (Don't Repeat Yourself) principle, which implies that no block of code should be written twice. In this article, we will explore how to write our own functions, pass information to them, and receive results to achieve reusable components.


What Are Functions and Why Do We Use Them?

Functions are the named blocks of code that are designed to perform a specific task. The code inside the function does not run unless the function is called explicitly. You can call a function as many times as needed without redefining it.

  • We use functions to enhance code reusability. Once you write a function, you can call it as many times as needed within the same or other programs.
  • They allow you to divide bigger programs into multiple smaller chunks called modules. This makes your code more manageable and understandable.
  • If you need to make changes to the code, you only need to do that within the function, which ultimately leads to enhanced code maintainability.

Types of Functions

There are two types of functions:

  1. Predefined functions.
  2. User-defined functions.

Predefined Functions

The predefined functions are the ones that the founders of a programming language have already designed. We have used various built-in functions in our programs so far, such as print(), set(), int(), append(), remove(), clear(), etc. The benefit of these functions is that we do not need to write hundreds of lines of code to perform a function.

User-Defined Functions

The user-defined functions are those that are created by the programmers themselves according to their needs. You can define as many functions in a program as needed and call them anywhere in the program.

Defining a Function

Syntax:


def function_name(parameters):
    statement(s)

In the above syntax,

  • def is a keyword used to define a function.
  • Function_name can be anything you like, but it follows the same rules as the variable names.
  • Parameters are the values that the function accepts when called. These are optional, so you can skip them.
  • Statements are the lines of code that you want to execute whenever the function is called.

Example:


def stars():
    print("******")  # Prints a line of stars

Calling a Function

To call a function, we simply call its name and provide the required arguments.

Syntax:


function_name(arguments)

In the above syntax,

  • Function_name refers to the name of the function you want to run.
  • Arguments are the values passed to the function. If there are no parameters in the function definition, you do not need to pass any arguments at the function call.

Example:


def stars():
    print("******")

stars()

Output:


******

Parameters and Arguments

Let's discuss these in a bit more detail since understanding these is highly crucial to writing efficient functions.

Parameters

The parameters are the variables that are defined during function declaration. They are used to hold the values passed to the function when called.

Example:


def print_stars(number_of_stars):
    for i in range(number_of_stars):
        print("*", end=" ")

In the above example,

  • Number_of_stars is a parameter whose value will be provided at the function call.
  • The end=" " in the print() statement is used to print the output in the same line.

Default Parameters

When you doubt that the user may not provide the arguments when a function is called, you can define default values for each parameter to avoid errors.

Example:


def greetings(name = "User"):  # Default Parameter
    print("Welcome ", name, "!")

greetings()  # No argument passed. The default value will be used

Output:


Welcome  User !

Please note that any default parameters must be defined after any non-default parameters because Python needs to know which argument belongs to which mandatory parameter.

Arguments

The arguments are the actual values that are passed to the function when called.

Example:


def print_stars(number_of_stars):
    for i in range(number_of_stars):
        print("*", end=" ")

print_stars(5)

In the above example,

  • The 5 in the function call is the argument, which is first stored in the number_of_stars parameter and then used in the function body to perform an action.

In Python, there are various types of arguments, which are as follows:

Positional Arguments

The arguments are passed in the strict order as the parameters are defined. We usually use these arguments in our programs.

Example:


def full_name(first_name, last_name):
    name = first_name + " " + last_name  # This is called the concatenation operator that combines two or more strings.
    print("Your full name is ", name)

full_name("John", "Smith")

Output:


Your full name is  John Smith

Keyword Arguments

In these arguments, we specifically name the parameter each argument belongs to.

Example:


def total_score(score_1, score_2):
    final_score = score_1 + score_2
    print("Your final score is ", final_score)

total_score(score_1=300, score_2=200)  #keyword arguments

Output:


Your final score is  500

Returning a Value From a Function

If you want to manipulate a value inside a function and use it somewhere in your program, you can return it from the function using the return statement.

The return statement immediately terminates the functions and sends the specified value back to the caller. It is defined in the function declaration.

Syntax:


def function_name(parameters):
    statement(s)
    return value

You can either return a variable or a value from a function.

Example:


def greetings(name = "User"):  # Default Parameter
    message = "Welcome " + name + "!"
    return message

greeting = greetings("John")  # return value will be stored in the greeting variable first
print(greeting)

Output:


Welcome John!

Scope Of the Variables

The scope in programming refers to the validity of a variable in a program. A variable can either be accessed throughout the program or just within the block it is defined in. These are called global and local scopes, respectively.

Local Scope

When a variable is defined inside a block, its scope is local, meaning that it can only be accessed and used within that scope.

For example, the 'message' variable in our previous example or the 'name' in the parameter can only be accessed within the greetings() function. If we try to call these variables outside of the function, it's going to generate a NameError exception.


def greetings(name = "User"):  # Default Parameter
    message = "Welcome " + name + "!"
    return message

print(message)

Output:


NameError: name 'message' is not defined

Global Scope

The global variables are the ones defined outside of any function and can be called and used anywhere inside the program, including functions. However, it is not considered a good practice to use the global variables inside functions directly. Instead, pass them as parameters.


username = "John"  # Global variable
def greetings(name = "User"):  # Default Parameter
    message = "Welcome " + name + "!"
    return message

print(greetings(username))

Creating a Simple Calculator Using Functions

Now that we have covered all the concepts related to functions in Python let's create a simple calculator with functions that take 2 numbers and an operator from the user as input and perform the specified calculations.


def user_input():  # Taking 2 numbers and an operator from the user
    fir_number = int(input("Enter the first number: "))
    sec_number = int(input("Enter the second number: "))
    oprtr = input("Enter an operator (+, -, *, /, %)")
    return fir_number, sec_number, oprtr  # returns a tuple

def add(number_1, number_2):  # Addition operator
    addition = number_1 + number_2
    return addition

def subtract(number_1, number_2):  # Subtraction operator
    difference = number_1 - number_2
    return difference

def multiply(number_1, number_2):  # Multiplication operator
    product = number_1 * number_2
    return product

def divide(number_1, number_2):  # Division operator
    quotient = number_1//number_2
    return quotient

def modulus(number_1, number_2):  # Modulus operator
    remainder = number_1 % number_2
    return remainder

def calculate(num1, num2, op):  # Performs the actual calculation
    if op == '+':  # Checks the operator passed and returns the corresponding result.
        return add(num1, num2)
    elif op == '-':
        return subtract(num1, num2)
    elif op == '*':
        return multiply(num1, num2)
    elif op == '/':
        return divide(num1, num2)
    elif op == '%':
        return modulus(num1, num2)
    else:  # If the user enters an operator other than the specified ones, it shows the following message.
        return "Invalid Operator!"

data = user_input()  # Taking input from user
first_number = data[0]  # Since the user_input() function returns a tuple, we use index numbers to access the corresponding data.
second_number = data[1]
operator = data[2]

result = calculate(first_number, second_number, operator)  # Storing the result in a variable

print(first_number, " ", operator, " ", second_number, " = ", result)  # Printing a well-formatted output.

Output:


Enter the first number: 50

Enter the second number: 10

Enter an operator (+, -, *, /, %): +
50   +   10  =  60

Bingo! We have really come far in our Python programming journey. You can now make your program perform a specific task multiple times without rewriting the code. Next up, we will look into file handling in Python. Stay tuned!


Sharpen Your Skills with These Next Guides