Alternating 1 and 0 Triangle in Python

Beginner
⏱️ 7 min read
📚 Updated: Sep 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo + Nested Loops

What You’ll Learn

The alternating 1 and 0 triangle prints 11111, 0000, 111, 00, 1 — a natural step after the rotating number pattern in Program 39. This tutorial covers modulo parity, shrinking inner-loop width, nested loops, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.

Shape Rule

Parity + shrinking width

Row 1 prints 11111, row 2 prints 0000, shrinking until a single 1 — odd rows are 1s, even rows are 0s.

Outer Loop

1..rows

for i in range(1, rows + 1): walks each row and supplies the parity value via i % 2.

Inner Loop

i..rows ascending

for _ in range(i, rows + 1): repeats the row digit rows - i + 1 times.

Modulo parity

i % 2

print(i % 2, end="") prints 1 on odd rows and 0 on even rows.

Live Preview

3–9 rows

Pick a row count and draw the alternating 1/0 triangle in the browser.

O(n²)

Complexity

Total digit prints = n(n+1)/2; extra memory stays O(1).

Introduction

An alternating 1 and 0 triangle prints odd rows filled with 1s and even rows filled with 0s, while each row gets shorter. With rows = 5, the output is 11111, 0000, 111, 00, 1.

In Python the outer loop runs i = 1..rows, the inner loop repeats i % 2 via range(i, rows + 1), then print() moves to the next line.

Why it matters?

It teaches modulo parity and shrinking inner-loop bounds — a key step after Program 39’s rotating rows.

Key Highlights

Parity rule

i % 2 picks 1 or 0 for the whole row.

Shrinking width

Inner loop starts at i and runs to rows.

vs Program 39

Program 39 rotates digits; Program 40 alternates binary digits by row parity.

Series Foundation

Follow Program 39; continue to Program 41 (square numbers pyramid) next.

In short: for each i from 1 to rows, print i % 2 repeatedly for range(i, rows + 1), then print().

📝 Problem & Approach

Given a positive integer rows (e.g. 5), print an alternating 1/0 triangle: odd rows are all 1s, even rows are all 0s, with each row one character shorter.

Python
# rows = 5 (conceptual shape)
# 11111
# 0000
# 111
# 00
# 1

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines and width of the first row.
iintOuter loop — row index from 1 to rows; also supplies parity via i % 2.
_Inner loop — repeats the row digit rows - i + 1 times via range(i, rows + 1).

Minimal workflow

Pseudocode
for i from 1 to rows:
    digit = i % 2
    for _ from i to rows:
        print digit
    print newline

Approach comparison

ApproachIdeaBest for
Nested loops + modulo11111, 0000, …Learning and interviews
User-input rowsint(input(...))Flexible console programs
Spaced outputprint(i % 2, end=" ")Easier reading per row

⚡ Quick Reference

GoalPattern
Walk rowsfor i in range(1, rows + 1):
Print parity digitprint(i % 2, end="")
Repeat per rowfor _ in range(i, rows + 1):
End the rowprint()
Spaced digitsprint(i % 2, end=" ")
Flip 1s and 0sprint(1 - (i % 2), end="")
Program 39 contrastRotating digits i..rows then wrap — not binary parity

📋 Fixed Rows vs User Input vs Spaced Output

Same alternating 1/0 triangle — different ways to control rows and formatting.

Outer loop
i = 1..rows

Supplies parity via i % 2

Inner loop
_ = i..rows

Shrinking row width each line

First row
i = 1

Longest row of 1s on top

Learning tip
i % 2

Odd → 1, even → 0

Context

When This Pattern Shows Up

Reach for this pattern when teaching modulo parity and shrinking inner-loop bounds.

  1. After Program 39

    Natural follow-up — alternating binary digits by row parity instead of rotating numbers.

  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

    Flip parity with 1 - (i % 2) or try per-column alternation with (i + j) % 2.

  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 row count between 3 and 9 and draw the alternating 1/0 triangle in the browser.

Try 4, 5, or 7. Max up to 9 in this preview.

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — fixed rows, user input, and spaced output variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating 1/0 triangle with nested loops and modulo.

Example 1 — Fixed rows = 5

Hard-coded row count — ideal for first demos and screenshots.

Python
rows = 5

for i in range(1, rows + 1):
    for _ in range(i, rows + 1):
        print(i % 2, end="")
    print()

How It Works

When i = 1 (odd), the inner loop prints 1 five times — output 11111. When i = 2 (even), it prints 0 four times — output 0000. The outer loop increases i each row, shortening the inner loop.

📈 User Input

Read the row count with input() instead of hard-coding 5.

Example 2 — User Input

Read rows with input() and int() (wrap in try/except ValueError in real apps).

Python
rows = int(input("Enter the number of rows: "))

for i in range(1, rows + 1):
    for _ in range(i, rows + 1):
        print(i % 2, end="")
    print()

How It Works

Same modulo inner-loop core as Example 1; only the source of rows changes from a literal to user input. Non-numeric input raises ValueError with bare int(input()) — use try/except for safer labs.

⚡ Spaced Output

Add a space between digits for easier reading on each row.

Example 3 — Spaced Characters

Keep rows = 5 but print each character followed by a space.

Python
rows = 5

for i in range(1, rows + 1):
    for _ in range(i, rows + 1):
        print(i % 2, end=" ")
    print()

How It Works

Only the print statement changes — print(i % 2, end=" ") instead of print(i % 2, end=""). Loop bounds and parity check stay the same as Example 1.

🧠 How the Algorithm Prints Rows

1

Set up

No imports needed for fixed rows; use input() when reading. Set rows = 5 and loop variable i.

Setup
2

Outer loop walks rows

for i in range(1, rows + 1): — ascending outer loop supplies parity via i % 2.

Row
3

Inner loop (repeat)

for _ in range(i, rows + 1): — repeats the row digit rows - i + 1 times.

Repeat
4

Parity check

print(i % 2, end="") prints 1 for odd rows and 0 for even rows.

Modulo
5

New line

print() ends the row after the inner loop finishes.

Break
=

Alternating 1/0 triangle complete

Rows shrink from rows characters to one — O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 5

Trace each outer-loop value of i, the inner-loop range, character count, parity, and full row output.

iInner loopCharPrintsRow output
11, 2, 3, 4, 51511111
22, 3, 4, 5040000
33, 4, 513111
44, 50200
55111

Prints per row = rows - i + 1 — total prints = n(n+1)/2 for n rows.

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: flip parity with 1 - (i % 2) to start rows with zeros.

2. Pattern Series Base

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

Example: continue to Program 41 for a square numbers pyramid.

3. Console Formatting Drills

Practice print vs row newline without complex math.

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

4. Spaced Output

Add spaces between digits once the two-loop structure works.

Example: use print(i % 2, end=" ") between digits on each row.

5. Complexity Intuition

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

Example: count printed digits for rows = 5 — total is 15 (5+4+3+2+1).

6. Input Validation Labs

Pair the pattern with input() return checks and positive-row checks.

Example: reject rows <= 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: trace i and i % 2 on paper for rows = 3 before coding — watch how parity and row width interact.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Remember range() Stop Is Exclusive

    Outer loop uses range(1, rows + 1); inner loop uses range(i, rows + 1) — the stop value is not included.

  2. 2. Call try/except ValueError

    Use try/except ValueError so bad input does not crash when converting rows.

  3. 3. Keep print() Outside the Inner Loop

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

  4. 4. Modulo for parity

    i % 2 is 1 on odd rows and 0 on even rows — flip with 1 - (i % 2).

  5. 5. Dry-Run rows = 3

    Trace i = 1, 2, 3 on paper before coding the full rows = 5 demo.

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 alternating 1/0 triangles.

  1. 1. Newline Inside the Inner Loop

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

    → Use print(i % 2, end="") for digits; print() only after the inner loop.

  2. 2. Wrong Inner Range

    range(1, rows + 1) on every row prints a full rectangle — the start must change with i.

    → Keep for _ in range(i, rows + 1): so each row shortens correctly.

  3. 3. 0-Based Outer Loop by Mistake

    for i in range(0, rows): shifts parity — row 1 becomes all 0s instead of 1s.

    → Use for i in range(1, rows + 1): so row 1 starts with 1s.

  4. 4. Forgetting the Row Break

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

    → Always end the row after the inner loop.

  5. 5. Bare 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.

rows = 1

Single digit row

Output is just 1 on one line.

rows = 0

Empty pattern

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

Negative

rows < 0

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

rows = 2

Smallest triangle

Two rows: 11 and 0.

Bad input

Non-numeric input

Bare int(input()) raises ValueError on bad input — use try/except first.

Large rows

Large row count

Each row prints rows - i + 1 characters — total work grows as n(n+1)/2.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Rotating number pattern

2. Square numbers pyramid

  • Continue with Program 41
  • Centered pyramid of squares

3. Flip parity

  • Start rows with 0 using 1 - (i % 2)
  • Same loops, inverted output

4. Checkerboard variant

  • Alternate per column with (i + j) % 2
  • Same outer loop, different inner logic

Notes

  • Parity rule. Outer loop: i = 1..rows. Inner loop: range(i, rows + 1). Digit: i % 2.
  • print(i % 2, end="") stays on the line; print() advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • Odd rows are all 1s, even rows are all 0s — compare with Program 39 where digits rotate each row.

Quick Takeaway: outer loop i = 1..rows, inner loop range(i, rows + 1) with print(i % 2, end=""), then print().

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–3)O(n²)O(1)
Smaller demo (Example 3)O(n²)O(1)
Wrap Up

🎉 Conclusion

The alternating 1 and 0 triangle is a compact nested-loop lesson: modulo parity picks the row digit while a shrinking inner loop shortens each line. Master the fixed-rows version, then try user input and spaced output.

Practice the three examples above, then continue to Program 41 for the square numbers pyramid.

Odd rows print 1, even rows print 0 — keep print(i % 2, end="") for digits and print() for the break.

💡 Best Practices

✅ Do

  • Use for i in range(1, rows + 1): in the outer loop
  • Inner: for _ in range(i, rows + 1): repeats the row digit
  • Use print(i % 2, end="") for digits and print() after each row
  • Validate rows ≥ 1 for interactive programs
  • Wrap int(input()) in try/except ValueError

❌ Don’t

  • Call print() inside the inner digit loop
  • Use range(0, rows) for the outer loop (shifts parity)
  • Forget that range() stop is exclusive
  • Ignore bad console input in user-facing demos
  • Skip the rows = 1 edge case

Key Takeaways

Knowledge Unlocked

Five things to remember about this alternating 1/0 triangle

Print the pattern the beginner-friendly way.

5
Core concepts
02

Outer loop

range(1, rows + 1)

Code
03

Inner loop

range(i, rows + 1)

Code
% 04

Parity

i % 2 picks digit

Logic
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

It prints i % 2 on each row. When i is odd the row is all 1s; when i is even the row is all 0s.
The inner loop runs range(i, rows + 1), printing rows - i + 1 characters per row — decreasing from rows down to 1.
Print 1 - (i % 2) instead of i % 2, or swap the if/else logic.
Program 39 rotates digits 1..rows per row. Program 40 prints only 1 or 0 per row based on parity, with shrinking row length.
Replace 5 with rows in the outer loop bound — see Example 2.
Use print(i % 2, end=" ") instead of print(i % 2, end="") — see Example 3.
O(n²) for n rows because total prints are 1 + 2 + ... + n = n(n+1)/2.
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.
Only one row prints — a single 1 on one line.

Did you Know? 🔊

Odd rows print 1, even rows print 0 — chosen with i % 2. Row i prints rows - i + 1 characters; total prints = n(n+1)/2.

Continue to Program 41

Move on to the square numbers pyramid in the Python number-pattern series.

Program 41 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