Mastering Python: Day 5 — Functions and Modules in Python

Risky Mulya Nugraha
3 min readSep 2, 2023

--

Welcome to Day 5 of your Python learning journey! Today, we’ll dive into the world of functions and modules, two essential concepts in Python programming that help you write organized and reusable code.

Part 1: Defining Functions

Functions are blocks of reusable code that perform a specific task. They help you break down your program into smaller, manageable parts. In Python, you can create your own functions using the def keyword. Functions can take parameters (inputs) and return values (outputs).

Example: Creating a Simple Function

# Define a function to calculate the square of a number
def square(x):
return x ** 2

# Call the function
result = square(5)
print("Square of 5:", result)

In this example, we define a square function that takes an input x and returns its square. Functions improve code readability and maintainability.

Part 2: Modules and Libraries

Modules are Python files containing reusable code, including variables, functions, and classes. You can import modules to use their functionality in your program. Python also provides a rich standard library, and you can extend Python’s capabilities by using third-party libraries.

Example: Importing and Using Modules

# Import the math module to access mathematical functions
import math

# Calculate the square root using the math module
root = math.sqrt(25)
print("Square root of 25:", root)

Here, we import the math module and use it to calculate the square root. Modules and libraries save you time by providing pre-built solutions to common problems.

Part 3: Practical Exercises with Functions and Modules

Let’s build on our previous exercises to enhance the calculator by implementing functions and modules. This will make our calculator more organized and reusable. We’ll create functions for different operations and encapsulate them within a custom module.

Step 1: Create a Calculator Module

Create a new Python file named calculator.py. This will be our custom module containing the calculator functions.

# calculator.py

def add(x, y):
return x + y

def subtract(x, y):
return x - y

def multiply(x, y):
return x * y

def divide(x, y):
if y == 0:
return "Division by zero is not allowed."
return x / y

Step 2: Use the Calculator Module in the Main Script

Now, let’s create a main script that imports and utilizes our calculator module. Additionally, we’ll create a user-friendly menu system for selecting an operation and inputting two numbers for calculation.

# main.py (Main Script)

# Import the calculator module
import calculator

# Display a menu for the user
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

# Get user input
choice = input("Enter choice (1/2/3/4): ")

# Get user input for numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

# Perform the selected operation using functions from the calculator module
if choice == '1':
result = calculator.add(num1, num2)
elif choice == '2':
result = calculator.subtract(num1, num2)
elif choice == '3':
result = calculator.multiply(num1, num2)
elif choice == '4':
result = calculator.divide(num1, num2)
else:
result = "Invalid input"

# Display the result
print(f"Result: {result}")

With this setup, the calculator functions (add, subtract, multiply, divide) are defined in the calculator module, and the main script (main.py) imports and uses these functions. This approach allows you to organize your code into separate modules, promoting code reusability and maintainability.

As you conclude Day 5, you'll have built a solid foundation in crafting functions, utilizing modules, and expanding your capabilities with libraries. Keep up the practice and explore more advanced concepts to enhance your proficiency. Next, we will delve into Error Handling and Exceptions in Python.

--

--