Number Pattern Fill with 5 Triangle Pattern in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Two Inner Loops

What You’ll Learn

The fill-with-5 number triangle pads each row with the maximum value so every line has width n — a natural step after alternating odd/even patterns. This tutorial covers the shape rule, two inner loops, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.

Shape Rule

Sequence + fill

Row 1 prints 5 5 5 5 5, row 2 prints 4 5 5 5 5, row 3 prints 3 4 5 5 5, and so on.

Outer Loop

n..1

for i in range(n, 0, -1) walks rows from the top (all fill) down to the full sequence.

Two Inner Loops

i..n then pad

for j in range(i, n + 1) prints the sequence; for j in range(1, i) fills with n.

print end= vs print()

Same line / next line

Numbers use print(j, end=" ") or print(n, end=" "); end each row with print().

Live Preview

1–15 width

Pick a triangle width and draw the fill-with-n pattern instantly in the browser.

O(n²)

Complexity

Each of n rows prints n numbers — total prints = ; extra memory stays O(1).

Introduction

A fill-with-5 number triangle prints an ascending sequence on each row, then pads the rest with the maximum value so every row has the same width. With n = 5, the output is 5 5 5 5 5, 4 5 5 5 5, 3 4 5 5 5, 2 3 4 5 5, 1 2 3 4 5.

In Python you use a descending outer loop, print j from i to n in the first inner loop, fill remaining slots with n in the second inner loop, then print() ends each row.

Why it matters?

It combines two inner loops with fixed row width — a step up from Program 18.

Key Highlights

Sequence Loop

for j in range(i, n + 1) prints ascending numbers.

Fill Loop

for j in range(1, i) pads with n.

Print Then Break

print(j, end=" ") or print(n, end=" ") in inner loops; print() after.

Series Foundation

Follow Program 18; continue to Program 20 (continuous number triangle).

In short: for each i from n down to 1, print j from i to n, fill i - 1 times with n, then call print().

📝 Problem & Approach

Given a positive integer n, print a fill-with-n triangle: each row prints an ascending sequence from i to n, then pads with n so every row has width n.

Python
# n = 5 (conceptual shape)
# 5 5 5 5 5
# 4 5 5 5 5
# 3 4 5 5 5
# 2 3 4 5 5
# 1 2 3 4 5
for i in range(n, 0, -1):
    for j in range(i, n + 1):
        print(j, end=" ")      # sequence i..n
    for j in range(1, i):
        print(n, end=" ")      # pad with n
    print()

Inputs & Outputs

ItemTypeDescription
nintTriangle width and fill value (typically ≥ 1).
Printed outputtextEach row has n spaced numbers — sequence then padding.

Minimal workflow

Pseudocode
for i from n down to 1:
    for j from i to n:
        print j + space
    for j from 1 to i - 1:
        print n + space
    print newline

Approach comparison

ApproachIdeaBest for
Two inner loops5 5 5 5 5, 4 5 5 5 5, …Learning and interviews
Variable nn = int(input(...))User-input version
Custom fillSeparate fill constantPad with a value other than n

⚡ Quick Reference

GoalPattern
Walk each rowfor i in range(n, 0, -1)
Print sequencefor j in range(i, n + 1): print(j, end=" ")
Fill paddingfor j in range(1, i): print(n, end=" ")
End the rowprint()
User inputn = int(input(...))
Custom fill valueprint(fill, end=" ") in second loop

📋 Sequence Loop vs Fill Loop vs Custom Fill

Same fill-with-n triangle — different ways to structure the padding.

Sequence
j = i..n

First inner loop prints ascending numbers

Fill
pad n

Second loop runs i - 1 times with n

Variable n
input

Replace hard-coded 5 with user input in Example 2

Learning tip
width n

Every row must print exactly n numbers

Context

When This Pattern Shows Up

Reach for this pattern when teaching two inner loops and fixed-width row padding.

  1. First lab exercise

    Natural follow-up after Program 18 — combines sequence printing with right padding.

  2. Nested-loop warm-up

    Outer/inner bound practice with an immediate visual check.

  3. Console I/O practice

    Combine loops with input() for a flexible row count.

  4. Gateway to variants

    Compare Program 18 (alternating odd/even) and Program 20 (continuous counter triangle) next.

  5. Not a UI layout tool

    This is a console teaching pattern — not how you build modern app screens.

Key benefit: one small program that locks in nested loops, output sequencing, and O(n²) thinking.

🔮 Live Preview

Choose a triangle width between 1 and 15 and draw the fill-with-n pattern in the browser.

Try 5, 7, or 10. Larger values still work up to 15.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — fixed width, user input, and custom fill constant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the fill-with-5 triangle with two inner loops.

Example 1 — Fixed n = 5

Hard-coded width — ideal for first demos and screenshots.

Python
n = 5

for i in range(n, 0, -1):
    for j in range(i, n + 1):
        print(j, end=" ")

    for j in range(1, i):
        print(n, end=" ")

    print()

How It Works

When i = 5, the sequence loop prints 5 once, then the fill loop runs 4 times — all 5s. When i = 3, the sequence prints 3 4 5, then two 5s pad the row. When i = 1, the sequence prints 1 2 3 4 5 with no fill needed. print() after both inner loops starts the next row.

📈 User Input

Read the triangle width with input() instead of hard-coding 5.

Example 2 — User Input

Read n with input() and int() (wrap in try/except ValueError in real apps); the fill value matches the width.

Python
n = int(input("Enter the triangle width: "))

for i in range(n, 0, -1):
    for j in range(i, n + 1):
        print(j, end=" ")

    for j in range(1, i):
        print(n, end=" ")

    print()

How It Works

Same nested-loop core as Example 1; only the source of n changes. Both the sequence end bound and the fill value use the same variable. Non-numeric input raises ValueError with bare int(input()) — use try/except for safer labs.

⚡ Custom Fill

Use a separate fill constant instead of always padding with n.

Example 3 — Custom Fill Constant

Pad with fill = 9 while the sequence still runs up to n = 5.

Python
n = 5
fill = 9

for i in range(n, 0, -1):
    for j in range(i, n + 1):
        print(j, end=" ")

    for j in range(1, i):
        print(fill, end=" ")

    print()

How It Works

Replace n with fill in the second inner loop only. The sequence loop still prints j from i to n; padding uses the custom constant.

🧠 How the Algorithm Prints Rows

1

Set up

print is built in; use input() when reading input. Set n (fixed or from input).

Setup
2

Outer loop (descending)

for i in range(n, 0, -1) walks from the all-fill top row down to the full sequence.

Row
3

Sequence + fill loops

Print j from i to n, then pad i - 1 times with n (or a custom fill value).

Sequence
4

New line

print() ends the row so the next outer iteration starts fresh.

Break
=

Fill triangle complete

Total prints: O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — n = 5

Trace each outer-loop value of i, the sequence printed, the fill count, and the final row.

iSequence (j = i..n)Fill count (i - 1)Row output
5545 5 5 5 5
44, 534 5 5 5 5
33, 4, 523 4 5 5 5
22, 3, 4, 512 3 4 5 5
11, 2, 3, 4, 501 2 3 4 5

Total number prints: 5 + 5 + 5 + 5 + 5 = 25 = .

Use Cases

Where this tiny pattern (and its loop structure) shows up beyond the homework prompt.

1. Teaching Nested Loops

Clearest visual proof that outer and inner bounds interact.

Example: change range(1, i + 1) and watch the shape change.

2. Pattern Series Base

Foundation for inverted, pyramid, diamond, and hollow variants.

Example: use (i + j) % 2 for row+column parity grids.

3. Console Formatting Drills

Practice print(..., end=" ") vs row newline without complex math.

Example: put print() inside the inner loop by mistake.

4. Character Substitution

Swap digits for letters, stars, or spaced output once the loop works.

Example: use print(j, end=" ") for spaced numbers on each row.

5. Complexity Intuition

Triangular totals make O(n²) concrete for beginners.

Example: count printed digits for n = 10 still → 55.

6. Input Validation Labs

Pair the pattern with try/except ValueError around int(input()) and positive-width checks.

Example: reject n <= 0 and re-prompt.

Pro Tip: when an interviewer asks for patterns, explain the outer/inner roles first — then write the loops. The story matters as much as the code.

Advantages

Why this pattern earns a permanent spot in beginner Python courses.

  1. 1. Instant Visual Feedback

    Wrong bounds show up immediately as a broken staircase.

  2. 2. Minimal Concepts

    Only loops and console output — no arrays or math libraries.

  3. 3. Easy to Extend

    Invert, center, hollow, or change the fill character with small edits.

  4. 4. O(1) Extra Memory

    Streaming output needs no storage beyond loop counters.

Pro Tip: learn the sequence loop first, then add the fill loop — compare with custom fill in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use n for both width and fill value unless you need a custom constant.

  2. 2. Prefer try/except ValueError

    Wrap int(input()) in try/except ValueError so bad input does not leave n unset.

  3. 3. Keep print() Outside

    Only call print() after the inner loop finishes the row.

  4. 4. Trace k on Paper

    Write row i, sequence j = i..n, and fill count i - 1 before coding.

  5. 5. Dry-Run One Small n

    Trace n = 5 on paper before coding larger demos.

Pro Tip: if the output is a vertical list of single digits per line, you almost certainly put print() inside the inner loop.

Common Pitfalls

Mistakes that commonly break fill-with-n number patterns.

  1. 1. Newline Inside the Inner Loop

    Each digit lands on its own line — you get a column, not a triangle.

    → Use print(j, end=" ") or print(n, end=" "); print() only after both inner loops.

  2. 2. Skipping the Fill Loop

    Rows have different widths — the top row may be short while the bottom is full.

    → Add for j in range(1, i) to pad with n after the sequence loop.

  3. 3. Wrong Fill Loop Bound

    range(1, i + 1) in the fill loop prints too many padding values.

    → Use range(1, i) so the fill runs exactly i - 1 times.

  4. 4. Forgetting the Row Break

    Omitting print() glues every number onto one endless line.

    → Always end the row after both inner loops.

  5. 5. Blind int(input())

    Letters or empty input raise ValueError with bare int(input()).

    → Catch ValueError and re-prompt on failure.

Edge Cases

Check these inputs before calling the solution done.

n = 1

Single digit

Output is just 1 on one line — no fill needed.

n = 0

Empty pattern

Outer loop never runs — print nothing or show a message.

Negative

n < 0

Treat as invalid; re-prompt instead of silent empty output.

Large n

Large width

Output grows as n² characters — fine for labs, noisy for huge n.

Bad input

Non-numeric input

int(input()) raises ValueError — validate with try/except first.

wrong range

Wrong sequence bound

Sequence must run range(i, n + 1), not range(1, i + 1).

No fill

Forgot second loop

Without the fill loop, top rows are shorter than the bottom row.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Alternating odd/even triangle

2. Continuous counter triangle

  • Single counter across all rows
  • Continue with Program 20

3. Custom fill value

  • Pad with a constant other than n
  • Compare output with Example 3

4. No trailing space

  • Print space only between numbers, not after the last
  • Harder follow-up after this page

Notes

  • Square total. Total prints = — each of n rows prints n numbers.
  • print(j, end=" ") stays on the line; print() advances — mix them carefully.
  • Validate n > 0 for interactive programs; n = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: descending outer loop, print sequence j = i..n, fill i - 1 times with n, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(n²)O(1)
Custom fill (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The fill-with-5 number triangle is a compact lesson in two inner loops: the first prints an ascending sequence, the second pads with the maximum value so every row has width n. Master the fixed-n version, then try user input and a custom fill constant.

Practice the three examples above, then continue to Program 20 for the continuous number triangle.

Run the sequence loop first, then the fill loop — use j < i for padding and validate n when reading input.

💡 Best Practices

✅ Do

  • Explain sequence loop vs fill loop before coding
  • Use print(j, end=" ") and print(n, end=" ")
  • Validate n ≥ 1 for interactive programs
  • Wrap int(input()) in try/except ValueError before using n
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call print() inside the inner digit loop
  • Skip the second inner loop
  • Use range(1, i + 1) in the fill loop
  • Skip the newline after each row
  • Ignore bad console input in user-facing demos
  • Skip the n = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this fill pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

i = n..1

Code
1 03

Sequence

j = i..n

Code
5 04

Fill

Pad i - 1 times

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

When i = 5, the sequence loop prints j = 5 once, then the fill loop runs 4 times — all values are 5, so the row is 5 5 5 5 5.
The first inner loop prints the increasing sequence i..n. The second fills remaining positions with n so every row has the same width.
When i = 1, the sequence loop prints j = 1 to 5 and the fill loop runs zero times — no padding needed.
print(j, end=" ") stays on the same line with a trailing space. print() ends the current line. Numbers use end=" "; the row break uses print() after both inner loops.
Replace the hard-coded 5 with a variable n (see Example 2) or any constant you prefer for padding (see Example 3).
Rows will have different widths — the top row may be short while the bottom row is full length.
Yes, but print rows in reverse order or adjust i from 1 to n and change which row prints first.
O(n²) for width n because each of n rows prints n numbers.
Use a try/except ValueError around int(input()) or check the raw string with .isdigit() before converting so bad input does not crash the script.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

Each row prints an ascending sequence i..n, then pads with n so every row has width n. The second inner loop runs i - 1 times — still O(n²) total prints.

Continue to Program 20

Move on to the continuous number triangle in the Python number-pattern series.

Program 20 tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful