Functions and Modules for Python Coding Beginners
Ready for the next leap?
In the last chapter, you controlled your program’s path with conditionals and loops (Control Flow Fundamentals for Python Coding).
Now we’ll unlock the real superpower of the python coding language: functions and modules.
By the end of this chapter, you’ll write clean, reusable code.
You will also plug in helpful tools from the standard library.
What you’ll learn and build today:
- Define functions with parameters and return values
- Understand scope and default arguments (with a crucial tip)
- Write docstrings and use help()
- Import and use modules (math, random, pathlib)
- Practice with a temperature converter and a roll_dice() utility
- Use try/except around user input for friendly error handling
Pro tip: Need a refresher on variables and types?
Skim Variables and Data Types in the Python Coding Language first.
Why functions matter in python coding
Functions are named blocks of code that run when you call them.
They help you:
- Avoid repetition (Don’t Repeat Yourself)
- Organize logic into clear, testable pieces
- Share and reuse code across files and projects
Your first function (def, parameters, return)
def greet(name):
"""Return a friendly greeting for the given name."""
return f"Hello, {name}!"
message = greet("Ada")
print(message) # Hello, Ada!
If you don’t have Python installed yet, no problem.
Run these examples in your browser using one of these top Python online IDEs.
- def starts a function definition
- name is a parameter (an input your function expects)
- return sends a result back to the caller. If you don’t return, Python returns None by default
Tip: Function names follow the same rules as variables (see Variables and Data Types in the Python Coding Language).
Docstrings and help()
A docstring is a short description of a function.
It appears as the first triple-quoted string in the body.
def area_circle(radius):
"""Compute the area of a circle given its radius (float)."""
import math
return math.pi * (radius ** 2)
print(help(area_circle)) # shows the docstring and signature
Docstrings are how tools (and teammates!) learn to use your function quickly.
The built-in help() reads docstrings and signatures so you don’t have to guess.
Parameters, arguments, and default values
You can add defaults so callers don’t always have to specify every argument.
def circumference(radius, precision=2):
"""Return the circle circumference rounded to precision."""
import math
value = 2 * math.pi * radius
return round(value, precision)
print(circumference(3)) # uses default precision=2
print(circumference(3, 4)) # override the default
print(circumference(radius=3)) # keyword argument
Important: Default arguments are evaluated only once.
This can surprise people when using mutable defaults (like lists).
For background and examples on why "default arguments are evaluated once", see this concise explanation.
Safer pattern for mutables:
def collect(item, bag=None):
if bag is None:
bag = [] # a fresh list each call
bag.append(item)
return bag
Return values: use them right away or save them
A function can return any data: numbers, strings, lists, dicts, whatever you need.
You can assign the result to a variable or use it immediately in an expression.
subtotal = 19.99
def add_tax(amount, rate=0.07):
return round(amount * (1 + rate), 2)
print(add_tax(subtotal)) # use immediately
with_tax = add_tax(subtotal) # or save it
Scope: where variables live
- Variables created inside a function are local to that function
- Variables outside a function are global to the module
- Prefer passing values in and returning results out
TAX_RATE = 0.07 # module-level (global) variable
def total_with_tax(amount):
tax = amount * TAX_RATE # tax is local
return amount + tax
print(total_with_tax(10)) # 10.7
Avoid using global inside functions unless necessary.
Clear inputs/outputs make testing and reuse easier.
Using modules in the python coding language
Modules are files full of useful code you can import.
The standard library gives you batteries-included tools.
math: precise calculations
import math
print(math.sqrt(16)) # 4.0
print(round(math.pi, 4)) # 3.1416
random: dice, shuffles, and choices
import random
print(random.randint(1, 6))
colors = ["red", "green", "blue"]
print(random.choice(colors))
pathlib: working with file paths (a quick peek)
from pathlib import Path
home = Path.home()
notes = home / "notes.txt"
print(notes.exists()) # True/False
We’ll go deeper on files and folders in Data Structures and Files in Python Coding.
Safer user input with try/except
User input is messy.
try/except lets you handle bad input without crashing.
def ask_int(prompt="Enter a whole number: "):
while True:
try:
return int(input(prompt)) # may raise ValueError
except ValueError:
print("Please type a number like 3 or 42.")
n = ask_int()
print("You entered:", n)
This small pattern keeps your programs friendly.
Short exercises: get hands-on
These mini-exercises reinforce key ideas, parameters, return values, modules, and error handling.
1) Reusable temperature converter
Goal: Write a tiny library you could reuse in other scripts.
def c_to_f(c):
"""Convert Celsius to Fahrenheit."""
return c * 9/5 + 32
def f_to_c(f):
"""Convert Fahrenheit to Celsius."""
return (f - 32) * 5/9
if __name__ == "__main__":
# quick manual test with input + try/except
try:
value = float(input("Temp value: "))
scale = input("Is that C or F? ").strip().lower()
if scale == "c":
print(c_to_f(value))
elif scale == "f":
print(f_to_c(value))
else:
print("Please type C or F.")
except ValueError:
print("Please enter a numeric temperature like 37.5.")
2) roll_dice() with random
Goal: Return a list of dice results, then print the total.
import random
def roll_dice(sides=6, rolls=2):
"""Roll a die with `sides` a number of `rolls` times and return the list."""
results = [random.randint(1, sides) for _ in range(rolls)]
return results
hand = roll_dice(6, 3)
print("Rolls:", hand, "Total:", sum(hand))
3) Circle helper using math
Goal: Practice imports, returns, and defaults.
import math
def circle_stats(radius, precision=3):
"""Return area and circumference rounded to `precision`."""
area = math.pi * radius ** 2
circum = 2 * math.pi * radius
return round(area, precision), round(circum, precision)
print(circle_stats(2)) # (12.566, 12.566)
Want more practice after your temperature converter and dice roller?
Check out these beginner-friendly Python exercises to reinforce functions, parameters, and returns.
Organizing your code into files and modules
- Put related functions in a file (module), e.g., utils.py
- Import them where needed: from utils import rolldice, cto_f
- Add a docstring at the top of each file to explain its purpose
- Use the name == "main" guard for quick manual tests (as shown in temperature.py)
- Keep scripts focused: one job per file is a great habit
Not sure how to create files yet?
Chapter 5 expands this with file paths and data work: Data Structures and Files in Python Coding.
After that, you’ll build a small, working project in Build a Mini Project in the Python Coding Language.
If you need environment setup tips, revisit Getting Started with the Python Coding Language.
Troubleshooting tips
- Getting NameError? Check spelling and scope (is the variable defined where you’re using it?).
- Seeing TypeError: unsupported operand? Revisit types from Variables and Data Types in the Python Coding Language.
- Odd behavior with defaults? Ensure you aren’t using a mutable default list/dict; use None and create inside the function.
- Random results look “stuck”? Ensure you’re calling random functions each run (and not storing one fixed value).
Recap checklist
- I can define functions with def, add parameters, and return values
- I know how scope works and avoid relying on global inside functions
- I can set default arguments and know the mutable-default caution
- I can write docstrings and use help() to learn a function quickly
- I can import and use math, random, and pathlib
- I can wrap user input with try/except to keep programs friendly
- I can save functions into .py files and import them into other scripts
Next up, we’ll combine your functions with lists, dicts, and actual files in Data Structures and Files in Python Coding.
You’re building real momentum in the python coding language. Nice work.
If you prefer experimenting in the browser as you practice and organize code, try one of these.
Additional Resources
- Default arguments are evaluated once (explanation), A clear discussion of how Python evaluates default parameters and why mutable defaults can surprise you.
- Exception handling basics and best practices (PDF), Handy reference for try/except/else/finally with practical advice for clean error handling.