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?
A 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
- Write a function called
is_even(num)that returnsTrueif the number is even, elseFalse - Write a function
average(numbers)that takes a list of numbers and returns the average - Create your own module called
math_helpers.pyand move your functions into it
Bonus: Ask ChatGPT to test your module or help you turn it into a CLI tool.
🛠 Recommended Free Tools
- 🔗 Python Functions – W3Schools
- 🔗 Real Python: Defining Functions
- 🔗 Python Modules – Programiz
- 🔗 ChatGPT: Refactor messy code, generate helper functions, or create a module layout
🏁 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.