5  Output

5.1 The Wall

Your AI-generated program ran without errors but the output was a mess. Numbers had too many decimal places. Columns did not line up. There were no blank lines between sections and everything ran together. You asked AI to “make it look nicer” and got code full of f"{value:>10.2f}", formatting syntax that looked like someone spilled punctuation on the keyboard.

You need to understand print() and string formatting, not because you will memorise every format code, but because AI uses them constantly and you need to know what you are looking at when you modify the output.

This chapter fixes that.

5.2 Thinking Session

5.2.1 Getting Oriented

NoteThinking Session Prompt

How does Python’s print() function work beyond the basics? I know print("hello") prints text, but AI-generated code uses things like sep=, end=, and f"" strings. Explain what these do and when they matter.

Your AI should cover three things: print() parameters (sep changes what goes between items, end changes what goes at the end, default is newline), f-strings (formatted string literals that embed expressions in {}), and format specifications (the : syntax inside {}).

5.2.2 Go Deeper

NoteThinking Session Prompt

Show me how f-strings work in Python. I want to understand the syntax inside the curly braces, how do I control decimal places, alignment, padding, and width? Give me examples I would actually use, not theoretical ones.

TipWhat to Look For

Key patterns: {value:.2f} for 2 decimal places, {text:<20} for left-aligned in 20 chars, {text:>20} for right-aligned, {text:^20} for centred. These appear in AI-generated table output, reports, and formatted displays.

NoteThinking Session Prompt

What is the difference between print(), f-strings, .format(), and % formatting in Python? AI sometimes uses different ones in the same code. Which should I use and which are outdated?

5.2.3 Challenge It

NoteThinking Session Prompt

What does this code print, and why?

print("Name", "Age", "Score", sep=" | ")
print(f"{'Alice':.<15}{85:>5}")
print("Loading", end="")
print(".", end="")
print(".", end="")
print(" Done!")
TipWhat to Look For

Line 1 prints Name | Age | Score (sep changes the separator). Line 2 prints Alice.......... 85 (left-aligned with dot fill, right-aligned number). Lines 3-5 print Loading.. Done! on one line (end=“” suppresses the newline). These are tricks AI uses to create formatted output.

5.2.4 What You Should Have Learned

  • print() has sep and end parameters that change formatting
  • f-strings are the modern way to embed values in text: f"Hello {name}"
  • Format specs control alignment, width, and decimal places: {value:.2f}
  • end="" prevents newlines, useful for progress indicators
  • .format() and % still exist but f-strings are preferred

5.3 The Gap

You can now read AI-generated output code and understand what all the formatting syntax does. When AI produces a table with aligned columns or a progress bar, you know how to adjust the widths, change the alignment, or add decimal places.

In the Building Session, you will give your chatbot a proper welcome screen with formatted output.

5.4 Building Session

5.4.1 The Spec

Add formatted output to your chatbot:

  • A welcome banner with the bot name centred in a bordered box
  • Display the user’s name and message count in aligned format
  • Show a separator line between the welcome and the conversation

5.4.2 Prompt It

NoteBuilding Session Prompt

Update my chatbot to v0.5. Add a formatted welcome screen when the bot starts:

  • A line of 50 equals signs
  • The bot name centred within 50 characters
  • “Your Python Assistant” centred below it
  • Another line of 50 equals signs
  • After asking the user’s name, show a status line: “User: {name}” left-aligned, “Messages: 0” right-aligned, all within 50 characters

Use f-strings with format specifications for the alignment. Keep the rest of the chatbot logic from v0.4.

5.4.3 Read the Code

Your AI will produce something like this:

"""PyBot v0.5: Formatted output."""
BOT_NAME = "PyBot"
VERSION = "0.5"
WIDTH = 50

print("=" * WIDTH)
print(f"{BOT_NAME:^{WIDTH}}")
print(f"{'Your Python Assistant':^{WIDTH}}")
print("=" * WIDTH)

user_name = input(f"{BOT_NAME}: What's your name? ")
message_count = 0

print(f"{'User: ' + user_name:<{WIDTH // 2}}"
      f"{'Messages: ' + str(message_count):>{WIDTH // 2}}")
print("-" * WIDTH)

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

    if user_input.lower() == "quit":
        print("-" * WIDTH)
        print(f"Goodbye, {user_name}! "
              f"({message_count} messages)")
        break

    message_count += 1

    try:
        number = int(user_input)
        response = f"{number} is {'even' if number % 2 == 0 else 'odd'}"
    except ValueError:
        response = f"You said '{user_input}'"

    print(f"{BOT_NAME}: {response}")
TipWhat to Notice

{BOT_NAME:^{WIDTH}} centres the text in a field of WIDTH characters. {:>{WIDTH // 2}} right-aligns in half the width. "=" * WIDTH repeats the character. A common pattern for separator lines. The WIDTH constant means you change one number to adjust all formatting.

5.4.4 Stretch It

NoteBuilding Session Prompt

After the conversation ends, display a summary table showing the message count, the user’s name, and the bot version, formatted with aligned columns and a border.

5.5 Your Chatbot So Far

  • Ch 1: Basic loop with greeting and quit
  • Ch 2: Docstring, constants, comments
  • Ch 3: Recognises numbers vs text
  • Ch 4: Remembers user name, tracks messages
  • Ch 5: Formatted welcome screen, aligned output

5.6 Quick Reference

# print() parameters
print("a", "b", "c", sep=", ")   # a, b, c
print("Loading", end="")          # no newline

# f-strings
name = "Alice"
print(f"Hello {name}")             # Hello Alice
print(f"{3.14159:.2f}")            # 3.14

# Alignment (within width of 20)
print(f"{'left':<20}")             # left-aligned
print(f"{'right':>20}")            # right-aligned
print(f"{'centre':^20}")           # centred
print(f"{'dots':.<20}")            # fill with dots

# Repetition
print("=" * 50)                    # 50 equals signs