RUNLOCALAIv38
->Will it run?Best GPUCompareTroubleshootStartLearnPulseModelsHardwareToolsBench
Run check
RUNLOCALAI

Independently operated catalog for local-AI hardware and software. Hand-written verdicts. Source-cited claims. Reproducible commands when we have them.

OP·Fredoline Eruo
DIR
  • Models
  • Hardware
  • Tools
  • Benchmarks
TOOLS
  • Will it run?
  • Compare hardware
  • Cost vs cloud
  • Choose my GPU
  • Prompting kits
  • Quick answers
REF
  • All buyer guides
  • Learn local AI
  • Methodology
  • Glossary
  • Errors KB
  • Trust
EDITOR
  • About
  • Author
  • How we make money
  • Editorial policy
  • Contact
LEGAL
  • Privacy
  • Terms
  • Sitemap
MAIL · MONTHLY DIGEST
Get monthly local AI changes
Monthly recap. No spam.
DISCLOSURE

Some links on this site are affiliate links (Amazon Associates and other first-class retailers). When you buy through them, we earn a small commission at no extra cost to you. Affiliate links do not influence our verdicts — there are cards we rate highly that we don't have affiliate relationships with, and cards that sell well that we refuse to recommend. Read more →

© 2026 runlocalai.coIndependently operated
RUNLOCALAI · v38
  1. >
  2. Home
  3. /Learn
  4. /Courses
  5. /Python for AI — Zero to Useful
  6. /Ch. 5
Python for AI — Zero to Useful

05. Functions

Chapter 5 of 36 · 20 min
KEY INSIGHT

Functions let you name and reuse logic. Default arguments reduce the number of functions you need to write. Use keyword arguments in function calls when the argument meaning is not obvious from position.

Defining Functions

def generate_prompt(system_instruction, user_input):
    """Generate a formatted prompt for an AI model."""
    return f"System: {system_instruction}\nUser: {user_input}"

prompt = generate_prompt("You are helpful.", "Explain gravity.")
print(prompt)

The docstring (triple quotes) documents what the function does. Write these.

Default Arguments

def call_model(prompt, model="gpt-4", temperature=0.7, max_tokens=100):
    """Simulate calling an AI model."""
    return {
        "model": model,
        "prompt": prompt,
        "temperature": temperature,
        "max_tokens": max_tokens,
        "response": f"[Simulated response to: {prompt[:20]}...]"
    }

# Use defaults
result = call_model("Hello")
print(result["model"])  # gpt-4

# Override specific defaults
result = call_model("Hello", temperature=0.2)

Returning Multiple Values

def parse_response(response_text):
    """Extract parts of an AI response."""
    return response_text[:50], response_text[50:100], response_text[100:]

start, middle, end = parse_response("This is a long response from an AI model.")

Keyword Arguments

Pass arguments by name for clarity:

result = call_model(
    prompt="Tell me a joke",
    model="gpt-4",
    temperature=1.0,
    max_tokens=50
)

Scope

Variables inside a function do not leak out:

def process():
    local_var = "I only exist here"
    print(local_var)

process()  # Works
# print(local_var)  # NameError

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

Local verification checkpoint

Run the smallest example from this chapter in a local workspace and record the package version, runtime, data path, and observed output. If the result depends on model size, vector count, CPU/GPU backend, or available memory, note that constraint beside the exercise so the lesson remains reproducible.

EXERCISE

Write a function calculate_cost(tokens, model, per_1k_tokens) that returns the cost. Add defaults for model="gpt-4" and per_1k_tokens=0.03. Call it with and without keyword arguments.

← Chapter 4
Control Flow
Chapter 6 →
Lists and List Comprehensions