(7) =

Chapter 7. Functions/Modules/Packages#

7.1 Python Functions#

Functions are the essential building blocks that make modules useful!

A function is like a mini-program that:

  • Takes some input (called parameters or arguments)

  • Does something with that input

  • Returns a result (optional)

Think of it like a recipe or a machine:

  • You put ingredients in (input)

  • Follow the steps (code inside the function)

  • Get a finished dish out (output)

Why Do We Use Functions?

  1. Avoid repetition - Write code once, use it many times

  2. Organization - Break big problems into smaller pieces

def greet():
    '''
    a funtion says hello!
    '''
    ###
    ###
    return "Hello, World"

message = greet()
print(message)
Hello, World
def greet_person(name):
    # name is input param, argument
    return f"Hello, {name}!"

greet_person('Levi')
'Hello, Levi!'
greet_person('Levi')


print('i am in classroom')

print('how are you?')

print(greet_person("Daniel"))
i am in classroom
how are you?
Hello, Daniel!
def ideal_gas(p, n, T):
    #pV = nRT
    R = 0.0821
    V = n*R*T / p
    return V

print(ideal_gas(1, 2, 100))


print(ideal_gas(2, 5, 200))
16.42
41.050000000000004
def add_numbers(a, b):
    result = a + b
    return result


sum1 = add_numbers(5, 3)
sum2 = add_numbers(10, 25)

print(sum1, sum2)
8 35
def ideal_gas(p, n, T, R=0.0821):
    #pV = nRT
    # R = 0.0821
    V = n*R*T / p
    return V

print(ideal_gas(1, 2, 100, 0.08))
16.0
# Example 1: Simple function with no parameters

# Example 2: Function with parameters

# Example 3: Function with multiple parameters

# Example 4: Function with default parameters

A Real Problem: Too Many Functions!#

Imagine you’re working on a big project and you create lots of useful functions:

# Imagine all these functions in one big file...

# Math functions
def add(a, b):
    return a + b

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

def calculate_area_circle(radius):
    return 3.14159 * radius * radius

# Text functions  
def make_uppercase(text):
    return text.upper()

def count_words(text):
    return len(text.split())

def reverse_text(text):
    return text[::-1]

# File functions
def read_file_size(filename):
    # This would read actual file size
    return f"Size of {filename}: 1024 bytes"

def create_backup(filename):
    # This would create a backup
    return f"Backup created for {filename}"

# Date functions
def get_current_year():
    return 2024

def days_until_new_year():
    return "45 days until New Year"

# Grade functions
def calculate_average(grades):
    return sum(grades) / len(grades)

def assign_letter_grade(average):
    if average >= 90: return "A"
    elif average >= 80: return "B"
    elif average >= 70: return "C"
    else: return "D"

print("😵 Wow! That's a lot of functions in one place!")
print("Problems with this approach:")
print("❌ Hard to find specific functions")
print("❌ File becomes very long and messy") 
print("❌ Difficult to work with teammates")
print("❌ Hard to reuse functions in other projects")
print("❌ Testing becomes complicated")
print("\n💡 Solution: MODULES! Let's organize these functions...")
😵 Wow! That's a lot of functions in one place!
Problems with this approach:
❌ Hard to find specific functions
❌ File becomes very long and messy
❌ Difficult to work with teammates
❌ Hard to reuse functions in other projects
❌ Testing becomes complicated

💡 Solution: MODULES! Let's organize these functions...

Modules and Libraries Overview

As your Python programs get bigger, you’ll want to organize your code better. Modules and libraries help you:

  1. Organize code - Split large programs into smaller, manageable files

  2. Reuse code - Use the same functions in multiple programs

  3. Use existing tools - Access thousands of pre-built functions and tools

  4. Collaborate - Share code with others easily

Think of modules like toolboxes - each one contains related tools (functions) for specific tasks.

The Python programming language allows you to install add-on tools known as libraries or packages that provide additional features. Each library contains one or more modules, and each module contains useful functions (and sometimes datasets).

Here’s how this hierarchy works:

🐍 Python
    └── 📚 Library (e.g., SciPy)
        └── 📄 Module (e.g., integrate)
            └── ⚙️ Function (e.g., quad, trapz)

Example:

  • PythonSciPy Libraryintegrate modulequad() function

    • scipy.integrate.quad() - integrates equations numerically

7.2 What are Modules?#

A module is simply a Python file (.py) that contains functions, variables, and classes that you can use in other programs.

Why use modules?

  • Avoid repetition - Write once, use many times

  • Organization - Keep related functions together

  • Readability - Smaller, focused files are easier to understand

  • Collaboration - Share useful functions with others

Example: Instead of writing the same math functions in every program, you can put them in a math_tools.py module and import them whenever needed.

# math_tools.py (this would be a separate file)
def add_numbers(a, b):
    return a + b

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

# main_program.py (your main program)
import math_tools

result = math_tools.add_numbers(5, 3)  # Uses function from module
import math

import os

import sys
import math_tools

result = math_tools.add_numbers(10, 20)
print(result)

result2 = math_tools.multiply_numbers(10, 20)
print(result2)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
Cell In[10], line 1
----> 1 import math_tools
      3 result = math_tools.add_numbers(10, 20)
      4 print(result)

ModuleNotFoundError: No module named 'math_tools'
import os
print(os.__file__)
/Users/hoon/miniconda3/envs/chemcomp/lib/python3.10/os.py
import math

print(math.__file__)
/Users/hoon/miniconda3/envs/chemcomp/lib/python3.10/lib-dynload/math.cpython-310-darwin.so
import math_tools
math_tools.__file__
'/Users/hoon/CHME212/cheme_comp_book/docs/chapter07/math_tools.py'
math_tools.MASS
100

7.2.1 Built-in Modules#

Python comes with many built-in modules ready to use. These are like pre-installed apps on your phone - they’re already there, you just need to import them.

Common Built-in Modules:

  • math - Mathematical functions

  • random - Generate random numbers

  • datetime - Work with dates and times

  • os - Interact with your operating system

  • json - Work with JSON data

Basic Import Syntax:

import module_name
result = module_name.function_name()
print("=== Math Module ===")
import math
print(math.sqrt(16))
print(math.pow(2,3))
print(math.pi)
print(math.ceil(4.3))
print(math.floor(4.7))
=== Math Module ===
4.0
8.0
3.141592653589793
5
4
print(f"\n=== Random Module ===")
import random

print(random.randint(1,10))
print(random.random())
=== Random Module ===
5
0.3572052361376383
# Random choice from a list
colors = ["red", "blue", "green", "yellow"]
print(f'Random color: {random.choice(colors)}')
# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
Random color: yellow
[4, 1, 2, 5, 3]
print(f"\n=== DateTime Module ===")
import datetime

now = datetime.datetime.now()
print(now)
print(now.year, now.month, now.day)
=== DateTime Module ===
2026-02-09 14:02:42.331529
2026 2 9
print(f"\n=== OS Module ===")
import os


current_dir = os.getcwd()
print(current_dir)

home_dir = os.path.expanduser('~')
print(home_dir)
=== OS Module ===
/Users/hoon/CHME212/cheme_comp_book/docs/chapter07
/Users/hoon

7.2.2 Different Ways to Import#

There are several ways to import modules, each with its own advantages:

Basic Import

import math
result = math.sqrt(25)  # Use module_name.function_name

Import with Alias (Nickname)

import math as m
result = m.sqrt(25)  # Shorter name

Import Specific Functions

from math import sqrt, pi
result = sqrt(25)  # Use function directly, no module name needed
print(pi)

Import All Functions (Use Carefully!)

from math import *
result = sqrt(25)  # Can use any function from math module

⚠️ Warning: from module import * can cause naming conflicts. It’s usually better to be specific about what you import.

# Different Ways to Import - Examples
import math

math.sqrt(49)
7.0
import math as m

m.sqrt(49)
7.0
import math_tools_unl_chme as mt
mt.add_numbers(10, 20)
mt.multiply_numbers(10,20)
200
from math_tools_unl_chme import add_numbers


# def add_numbers(a, b):
#     return a - b

add_numbers(10, 20)
30

7.2.3 Creating Your Own Modules#

Creating your own modules is easy! Just save functions in a .py file and import them in other programs.

Step-by-Step Example:

Step 1: Create a file called my_functions.py with some functions:

# my_functions.py (this would be a separate file)

def greet(name):
    """Greet someone with their name"""
    return f"Hello, {name}! Nice to meet you."

def calculate_area(length, width):
    """Calculate area of a rectangle"""
    return length * width

def is_even(number):
    """Check if a number is even"""
    return number % 2 == 0

# You can also include variables
FAVORITE_COLOR = "blue"
LUCKY_NUMBER = 7

Step 2: Use your module in another program:

# main_program.py (your main program)
import my_functions

# Use the functions
message = my_functions.greet("Alice")
area = my_functions.calculate_area(5, 3)
check = my_functions.is_even(4)

print(message)
print(f"Area: {area}")
print(f"Is 4 even? {check}")
print(f"Favorite color: {my_functions.FAVORITE_COLOR}")
import my_functions


print(my_functions.greet("Juan"))
print(my_functions.is_even(4))
print(my_functions.LUCKY_NUMBER)
Hello, Juan! Nice to meet you.
True
7
from my_functions import calculate_area

# my_functions.calculate_area

calculate_area(10, 20)
200
import functions.chme212_functions
from functions import chme212_functions
chme212_functions.greet('Danielle')
'Hello, Danielle! Nice to meet you.'

7.3 What are Libraries?#

A library is a collection of related modules organized in folders. Think of it like a filing cabinet:

  • Library = Filing cabinet (main folder)

  • Modules = Individual files in the cabinet

  • Functions = Specific documents in each file

Library Structure Example:#

my_project/
    __init__.py          # Makes it a library
    math_tools/          # Library folder
        __init__.py      # Makes it a library
        basic_math.py    # Module
        advanced_math.py # Module
    text_tools/          # Another library
        __init__.py      # Makes it a library
        formatting.py    # Module
        analysis.py      # Module

Common Python Libraries:#

  • NumPy - Numerical computing

  • Pandas - Data analysis

  • Matplotlib - Creating graphs and charts

  • Requests - Making web requests

  • Flask - Building web applications

Installing Libraries:#

Most packages need to be installed first:

pip install package_name

For example:

pip install numpy
pip install pandas
pip install matplotlib
# Examples of Popular Packages
# Note: Some packages might not be installed in this environment

print("=== Exploring Library Usage ===")

# Check what packages are available
import sys
print(f"Python version: {sys.version}")

print(f"\n=== Standard Library Packages ===")
# These come with Python automatically

# Collections - useful data structures
from collections import Counter
words = ["apple", "banana", "apple", "cherry", "banana", "apple"]
word_count = Counter(words)
print(f"Word counts using Counter: {word_count}")
print(f"Most common word: {word_count.most_common(1)}")

7.4 Best Practices for Modules and Packages#

7.4.1 Organizing Your Code#

Good Module Design:

  • One purpose per module - Keep related functions together

  • Clear naming - Use descriptive module names

  • Documentation - Add docstrings to explain what functions do

  • Keep it simple - Don’t make modules too complex

7.4.2 Import Best Practices#

DO:

import math                    # Clear and explicit
from datetime import datetime  # Import specific functions you use
import numpy as np            # Standard alias

DON’T:

from math import *            # Unclear what functions are available
import veryLongModuleName     # Use an alias instead

7.4.3 Module Template#

Here’s a good template for creating your own modules:

# my_module.py
"""
Brief description of what this module does.

Author: Your Name
Date: Today's Date
"""

# Constants (use UPPERCASE)
DEFAULT_VALUE = 42
MAX_ATTEMPTS = 3

def main_function(parameter):
    """
    Brief description of what this function does.
    
    Args:
        parameter: Description of the parameter
        
    Returns:
        Description of what is returned
    """
    # Function implementation here
    return result

# Test code (only runs when module is executed directly)
if __name__ == "__main__":
    # Test your functions here
    print("Testing the module...")
    result = main_function("test")
    print(f"Result: {result}")

7.5 Summary and Next Steps#

What We’ve Learned#

In this chapter, we explored the powerful world of Python modules and packages:

  1. Built-in Modules: Python comes with many useful modules ready to use (math, random, datetime, os, json, collections)

  2. Import Methods: Different ways to bring functionality into your code:

    • import module_name

    • from module_name import function_name

    • import module_name as alias

  3. Custom Modules: How to create your own modules to organize code

  4. Libraries: Collections of modules that work together

  5. Best Practices: Writing clean, documented, and maintainable code

Remember#

Programming is like building with LEGO blocks - modules are your reusable pieces that you can combine in endless ways to create amazing things! 🐍✨