Part 6: Functions and Modules — Organize and Reuse Your Code (with AI to Help You Refactor)

By now, your code is starting to grow — which means it’s time to get organized. In this part, you’ll learn how to:

  • Create and use your own functions
  • Pass data in and out using parameters and return values
  • Split your code into modules
  • Use AI tools like ChatGPT to help write and refactor functions

🧠 What Is a Function?

A function is a reusable block of code that performs a specific task. You define it once and can call it multiple times.

def greet(name):
print(f"Hello, {name}!")

To call it:

greet("Alice")

🔄 Parameters and Return Values

Functions can accept input and return output:

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

result = add(3, 5)
print(result) # Output: 8

Use return to send data back to the caller. Once Python hits return, the function stops running.


🧠 AI Tip: Ask ChatGPT to Refactor Your Code

Paste a block of code and ask:

“Can you convert this into a function with proper parameters and return values?”

This will teach you how to spot repetition and extract reusable logic — a key step in writing clean code.


⚙️ What Is a Module?

module is a Python file that contains functions, variables, or classes. You can import a module into another Python file using import.

import math

print(math.sqrt(25)) # Output: 5.0

You can also create your own module:

  • Save a file as tools.py:
def greet(name):
    return f"Hello, {name}!"
  • Then use it in another file:
from tools import greet
print(greet("Willy"))

🤖 AI Tip: Build Function Templates with AI

Try:

“Write a Python function that calculates BMI from weight and height, and returns the category.”

Then ask ChatGPT to:

  • Add error handling
  • Add input prompts
  • Turn it into a reusable module

🎯 Practice Challenge

  1. Write a function called is_even(num) that returns True if the number is even, else False
  2. Write a function average(numbers) that takes a list of numbers and returns the average
  3. Create your own module called math_helpers.py and move your functions into it

Bonus: Ask ChatGPT to test your module or help you turn it into a CLI tool.


🛠 Recommended Free Tools


🏁 Coming Up in Part 7…

Next time, we’ll learn how to handle errors like a pro and work with files — so your apps can save, load, and process real data. We’ll also explore how AI can simulate file content and even generate logs or test data for you.

Share the Post:

Related Posts

Join the Codexa Crew – It’s free!

Stay Updated with the Latest in Tech & Automation

Be the first to know when new content drops on Green Codexa!