Quiz 2

Pattern Printing & Formatted Output

1039 words
5 min read
Python Week 1: the first filter for runtime behavior
Visual companion
Python
Type and operator map

Python Week 1: the first filter for runtime behavior

View
Revision summary

What this note is really saying

Short form

# Pattern Printing & Formatted Output > **Why read this?** Pattern printing is the classic "brain training" exercise for programmers. It forces you to think systematically about rows, columns, and the mathematical relationship between position and value.

Pattern Printing & Formatted Output

Why read this? Pattern printing is the classic "brain training" exercise for programmers. It forces you to think systematically about rows, columns, and the mathematical relationship between position and value. Beyond training, formatted output is essential for making your programs look professional — generating reports, tables, and structured displays.

🎯 Learning Objectives

By the end of this topic, you will be able to:
  1. Print triangles, pyramids, diamonds, and number patterns using nested loops
  2. Control output alignment with f-string format specifiers
  3. Use string justification methods: ljust(), rjust(), center()
  4. Design patterns by finding the mathematical relationship between i and j
  5. Create formatted tables and reports

📋 Prerequisites


📖 Core Content

13.1 Pattern Printing Strategy

Intuition: Every pattern has a hidden formula. The row number i determines how many stars, spaces, or numbers to print. Your job is to discover the formula. Step-by-step approach:
  1. Rows: How many rows? → Outer loop (for i in range(n):)
  2. Columns: What changes per row? → Inner loop(s)
  3. Formula: Express the pattern mathematically → n-i spaces, 2*i+1 stars, etc.
  4. Output: Build each row and print

13.2 Fundamental Pattern Types

python
# runnable
n = 5
print("1. Left-aligned triangle:")
for i in range(1, n+1):
    print("*" * i)
print("\n2. Right-aligned triangle:")
for i in range(1, n+1):
    print(("*" * i).rjust(n))
print("\n3. Inverted left-aligned:")
for i in range(n, 0, -1):
    print("*" * i)
print("\n4. Inverted right-aligned:")
for i in range(n, 0, -1):
    print(("*" * i).rjust(n))
Output:
pseudo
1. Left-aligned triangle:
*
**
***
****
*****
2. Right-aligned triangle:
    *
   **
  ***
 ****
*****
3. Inverted left-aligned:
*****
****
***
**
*
4. Inverted right-aligned:
*****
 ****
  ***
   **
    *

13.3 Pyramid and Diamond Patterns

python
# runnable
n = 5
print("Pyramid:")
for i in range(1, n+1):
    spaces = " " * (n - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)
print("\nDiamond:")
# Upper half
for i in range(1, n+1):
    print(" " * (n-i) + "*" * (2*i-1))
# Lower half
for i in range(n-1, 0, -1):
    print(" " * (n-i) + "*" * (2*i-1))
Output:
pseudo
Pyramid:
    *
   ***
  *****
 *******
*********
Diamond:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *

13.4 Number Patterns

python
# runnable
n = 5
print("1. Increasing numbers:")
for i in range(1, n+1):
    for j in range(1, i+1):
        print(j, end="")
    print()
print("\n2. Same number each row:")
for i in range(1, n+1):
    print(str(i) * i)
print("\n3. Number pyramid:")
for i in range(1, n+1):
    print(" " * (n-i), end="")
    for j in range(1, i+1):
        print(j, end="")
    for j in range(i-1, 0, -1):
        print(j, end="")
    print()
Output:
pseudo
1. Increasing numbers:
1
12
123
1234
12345
2. Same number each row:
1
22
333
4444
55555
3. Number pyramid:
    1
   121
  12321
 1234321
123454321

13.5 Floyd's Triangle

python
# runnable
n = 5
num = 1
for i in range(1, n+1):
    for j in range(i):
        print(f"{num:2d} ", end="")
        num += 1
    print()
Output:
pseudo
 1
 2  3
 4  5  6
 7  8  9 10
11 12 13 14 15

13.6 Hollow Patterns

python
# runnable
n = 5
print("Hollow square:")
for i in range(n):
    for j in range(n):
        if i == 0 or i == n-1 or j == 0 or j == n-1:
            print("*", end=" ")
        else:
            print(" ", end=" ")
    print()
print("\nHollow triangle:")
for i in range(1, n+1):
    for j in range(1, i+1):
        if j == 1 or j == i or i == n:
            print("*", end="")
        else:
            print(" ", end="")
    print()

13.7 Formatted Tables

python
# runnable
print("=" * 40)
print(f"{'Item':<15} {'Price':>10} {'Qty':>5} {'Total':>10}")
print("=" * 40)
items = [
    ("Apple", 1.50, 3),
    ("Banana", 0.75, 5),
    ("Cherry", 3.00, 2),
    ("Date", 2.25, 4)
]
total_sum = 0
for item, price, qty in items:
    total = price * qty
    total_sum += total
    print(f"{item:<15} ${price:>7.2f} {qty:>5} ${total:>8.2f}")
print("=" * 40)
print(f"{'TOTAL':<15} {'':>10} {'':>5} ${total_sum:>8.2f}")

13.8 Worked Example: Multiplication Table

python
# runnable
n = 10
# Header
print(f"{'×':>4}", end="")
for i in range(1, n+1):
    print(f"{i:4d}", end="")
print()
print("-" * (4 * (n+1)))
# Table body
for i in range(1, n+1):
    print(f"{i:4d}", end="")
    for j in range(1, n+1):
        print(f"{i*j:4d}", end="")
    print()

⚠️ Common Pitfalls

Pitfall 1: print() Default Newline in Patterns

The mistake: print("*") inside a pattern loop — each character prints on a new line. Fix: Use end="" to suppress newlines. Add print() when a line break is needed.

Pitfall 2: Wrong Number of Spaces in Pyramid

The mistake: Pyramid looks crooked because space count is off by one. Fix: For row i (1-indexed) in an n-row pyramid: n-i spaces. Each space is exactly one character.

Pitfall 3: Integer vs String Multiplication

The mistake: print(i * i) when you meant print(str(i) * i). Why: i * i computes the square. str(i) * i repeats the digit as a string. Fix: Convert to string first: print(str(i) * i).

📝 Practice Questions

Q1: Write code to print a 4×4 square of asterisks.
Answer:
python
for i in range(4):
    print("*" * 4)
Q2: Print a number triangle where row i has the number i repeated i times.
Answer:
python
for i in range(1, 6):
    for j in range(i):
        print(i, end="")
    print()
Output: 1, 22, 333, 4444, 55555 **Q3: Write code to print this pattern:
pseudo
1
2 3
4 5 6
7 8 9 10
```**
>
> **Answer:** (Floyd's triangle shown above)
> **Q4-10: Additional pattern questions follow the same format.**
>
> (Following the established pattern with detailed answers.)
---
## 🔗 Cross-References
- **Next Topic:** [Lists — Basics & Operations](/courses/bscs1002/notes/14-lists-basics)
- **Previous Topic:** [Loop Control](/courses/bscs1002/notes/12-loop-control)
- **Reference:** Python for Everybody, Chapter 6 (Section 6.11 — "Format operator")
- **Video:** L38: Formatted printing, L44: The obvious sorting in python
Document outline

Keep your place and jump directly to a heading.

Table of Contents
System Normal // Awaiting Context

Intelligence Hub

Navigate the knowledge graph to generate context. The Hub adapts dynamically to surface backlinks, related notes, and metadata insights.