8  Using Functions

8.1 The Wall

AI called len(), range(), sorted(), enumerate(), and zip() in a single block of code. You knew they were functions because of the parentheses, but you had no idea what they returned. You tried changing the arguments and got unexpected results. You looked up one function, understood it, then hit another you did not recognise.

AI uses Python’s built-in functions constantly. If you do not know what is available and what each function returns, you are reading AI-generated code through fog.

This chapter fixes that.

8.2 Thinking Session

8.2.1 Getting Oriented

NoteThinking Session Prompt

What are the most commonly used built-in functions in Python? Not all of them. Just the 10-15 that appear most often in AI-generated code. For each one, tell me what it does, what it returns, and give me a one-line example.

Your AI should cover: print(), input(), len(), type(), int(), float(), str(), range(), list(), sorted(), enumerate(), zip(), max(), min(), sum(). You already know some of these from earlier chapters. The new ones matter because AI uses them as building blocks.

8.2.2 Go Deeper

NoteThinking Session Prompt

Explain range(), enumerate(), and zip() in Python. These appear in AI-generated loops all the time and I do not fully understand them. Show me what each one produces and when I would choose one over another.

TipWhat to Look For

range(5) produces 0, 1, 2, 3, 4. enumerate(items) produces (0, "first"), (1, "second"), ..., index and value together. zip(list1, list2) pairs elements from two lists. These are the three loop helpers AI reaches for constantly.

NoteThinking Session Prompt

I see AI using .lower(), .strip(), .split(), .join(), .replace() on strings. Are these functions or something else? What is the difference between len(text) and text.lower()?

8.2.3 Challenge It

NoteThinking Session Prompt

What does each line produce?

len("hello")
len([1, 2, 3])
list(range(3))
sorted([3, 1, 2])
sorted("python")
list(enumerate(["a", "b", "c"]))
list(zip([1, 2], ["x", "y"]))
TipWhat to Look For

len("hello") is 5. len([1, 2, 3]) is 3. list(range(3)) is [0, 1, 2]. sorted([3, 1, 2]) is [1, 2, 3]. sorted("python") is ['h', 'n', 'o', 'p', 't', 'y']. It sorts characters. enumerate gives [(0, 'a'), (1, 'b'), (2, 'c')]. zip gives [(1, 'x'), (2, 'y')].

8.2.4 What You Should Have Learned

  • Built-in functions are called with function(arguments)
  • Methods are called on objects with object.method(arguments)
  • len(), type(), range(), sorted() work on many types
  • enumerate() and zip() are loop helpers you will see everywhere
  • Functions return values. You can store the result or use it inline

8.3 The Gap

You now have a vocabulary of the built-in functions AI reaches for most often. When you see sorted(data, key=lambda x: x["age"]) in AI-generated code, you know sorted() returns a new sorted list, key tells it what to sort by, and lambda creates a small anonymous function. You may not understand lambda fully yet, but you know what the overall line does.

In the Building Session, you will use built-in functions to add text processing to your chatbot.

8.4 Building Session

8.4.1 The Spec

Add built-in function usage to your chatbot:

  • Use len() to measure message length
  • Use .split() to count words
  • Use .lower() and .strip() for input cleaning (already started in Ch 6)
  • Use sorted() to show conversation stats alphabetically

8.4.2 Prompt It

NoteBuilding Session Prompt

Update my chatbot to v0.8. Add text processing using built-in functions:

  • Count the number of words in each message using split()
  • For the “stats” command, show: total messages, total words (sum across all messages), average words per message
  • Store all unique words the user has used (use a set)
  • For a “words” command, show the 5 most recently added unique words using sorted() and list slicing

Keep the existing features from v0.7.

8.4.3 Read the Code

Your AI will produce something like this:

"""PyBot v0.8: Built-in function processing."""
BOT_NAME = "PyBot"
VERSION = "0.8"

user_name = input(f"{BOT_NAME}: What's your name? ").strip()
while not user_name:
    user_name = input("Please enter your name: ").strip()

print(f"Hello, {user_name}! Type 'help' for commands.")

message_count = 0
total_words = 0
unique_words = set()

while True:
    user_input = input(f"{user_name}: ").strip()

    if not user_input:
        continue

    command = user_input.lower()

    if command == "quit":
        print(f"{BOT_NAME}: Goodbye, {user_name}!")
        break
    elif command == "help":
        print(f"{BOT_NAME}: Commands: quit, help, stats, words")
        continue
    elif command == "stats":
        avg = total_words // max(message_count, 1)
        print(f"{BOT_NAME}: Messages: {message_count}, "
              f"Words: {total_words}, Avg: {avg}/msg")
        continue
    elif command == "words":
        recent = sorted(unique_words)[-5:]
        print(f"{BOT_NAME}: Recent words: {', '.join(recent)}")
        continue

    message_count += 1
    words = user_input.split()
    word_count = len(words)
    total_words += word_count
    unique_words.update(w.lower() for w in words)

    print(f"{BOT_NAME}: ({word_count} words) "
          f"You said '{user_input}'")
TipWhat to Notice

.split() breaks a string into a list of words. len(words) counts them. set() stores unique values. unique_words.update() adds without duplicates. sorted() returns a sorted list, and [-5:] takes the last 5 items. max(message_count, 1) prevents division by zero.

8.4.4 Stretch It

NoteBuilding Session Prompt

Add an “info” command that takes a word as argument (e.g., “info python”). Use len() to show the word’s character count, and check if it is in the unique_words set.

8.5 Your Chatbot So Far

  • Ch 1-4: Loop, structure, types, name memory
  • Ch 5-6: Formatted output, input validation
  • Ch 7: Operators, keyword matching
  • Ch 8: Word counting, unique words, stats commands

8.6 Quick Reference

# Common built-ins
len("hello")          # 5
type(42)              # <class 'int'>
range(5)              # 0, 1, 2, 3, 4
sorted([3, 1, 2])     # [1, 2, 3]
max(3, 7, 2)          # 7
min(3, 7, 2)          # 2
sum([1, 2, 3])        # 6
abs(-5)               # 5

# Loop helpers
for i, item in enumerate(items):
    print(f"{i}: {item}")

for a, b in zip(list1, list2):
    print(f"{a} -> {b}")

# String methods
"hello world".split()       # ["hello", "world"]
" ".join(["a", "b"])        # "a b"
"Hello".lower()             # "hello"
"  hi  ".strip()            # "hi"
"hello".replace("l", "L")   # "heLLo"