Alternating Odd/Even Number Triangle Pattern in Python

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Modulo Operator

What You’ll Learn

The alternating odd/even number triangle switches row parity to print odd or even sequences — a natural step after left-shifted odd patterns. This tutorial covers the shape rule, loop structure, a live preview, algorithm steps, worked Python examples, edge cases, and complexity.

Shape Rule

i % 2 picks parity

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

Outer Loop

1..rows

for i in range(1, rows + 1) makes each new row one number longer than the previous.

Inner Loop + k

k += 2 sequence

for j in range(1, i + 1) prints k, then k += 2 keeps odd or even parity on each row.

print end= vs print()

Same line / next line

Numbers use print(k, end=" "); end each row with print().

Live Preview

1–20 rows

Pick a row count and draw the alternating odd/even triangle instantly in the browser.

O(n²)

Complexity

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

Introduction

An alternating odd/even number triangle grows each row by one number while switching between odd and even sequences using row parity. With rows = 5, the output is 1, 2 4, 1 3 5, 2 4 6 8, 1 3 5 7 9.

In Python you pick start value k with i % 2, print k in the inner loop, update k += 2, then print() ends each row.

Why it matters?

It combines parity checks with growing row width — a step up from Program 17.

Key Highlights

Row Parity

i % 2 picks odd start 1 or even start 2.

k += 2

Stays odd-only or even-only within each row.

Print Then Break

print(k, end=" ") in the inner loop; print() after.

Series Foundation

Follow Program 17; continue to Program 19 (fill-with-5 triangle).

In short: for each row i from 1 to rows, set k from i % 2, print k then k += 2 for i numbers, then call print().

📝 Problem & Approach

Given a positive integer rows, print an alternating odd/even triangle: odd rows print odd numbers starting at 1, even rows print even numbers starting at 2, each row has i numbers with k += 2.

Python
# rows = 5 (conceptual shape)
# 1
# 2 4
# 1 3 5
# 2 4 6 8
# 1 3 5 7 9
for i in range(1, rows + 1):
    if i % 2 == 0:
        k = 2
    else:
        k = 1
    for j in range(1, i + 1):
        print(k, end=" ")
        k += 2
    print()

Inputs & Outputs

ItemTypeDescription
rowsintNumber of triangle lines to print (typically ≥ 1).
Printed outputtextEach row has i spaced numbers — odd or even by row parity.

Minimal workflow

Pseudocode
for i from 1 to rows:
    if i is even: k = 2 else k = 1
    for j from 1 to i:
        print k + space
        k += 2
    print newline

Approach comparison

ApproachIdeaBest for
Parity + k += 21, 2 4, 1 3 5, …Learning and interviews
Conditional startk = 2 if i % 2 == 0 else 1Compact user-input version
Flip paritySwap odd/even row assignmentEven rows odd, odd rows even

⚡ Quick Reference

GoalPattern
Walk each rowfor i in range(1, rows + 1)
Pick start by parityif i % 2 == 0: k = 2 else: k = 1
Print and stepprint(k, end=" "); k += 2
End the rowprint()
Conditional shortcutk = 2 if i % 2 == 0 else 1
Flip parity rowsk = 1 if i % 2 == 0 else 2

📋 if/else vs Conditional vs Flip Parity

Same alternating triangle — different ways to set the row start value k.

i % 2
parity

Odd row → k=1, even row → k=2

k += 2
sequence

Keeps odd or even within the row

if/else expr
compact

One-line start pick in Example 2

Learning tip
reset k

Set k fresh each outer-loop iteration

Context

When This Pattern Shows Up

Reach for this pattern when teaching row parity and the k += 2 sequence inside nested loops.

  1. First lab exercise

    Natural follow-up after Program 17 — combines parity with growing row width.

  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 17 (left-shifted odds) and Program 19 (fill-with-5 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 row count between 1 and 20 and draw the alternating odd/even triangle in the browser.

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

Live result
Press "Draw pattern".

Examples Gallery

Three complete Python programs — fixed row count, compact conditional expression user input, and flipped parity variant. Click View Output to reveal sample console results.

📚 Getting Started

Print five rows of the alternating odd/even triangle with i % 2 and k += 2.

Example 1 — Fixed rows = 5

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

Python
rows = 5

for i in range(1, rows + 1):
    if i % 2 == 0:
        k = 2
    else:
        k = 1

    for j in range(1, i + 1):
        print(k, end=" ")
        k += 2
    print()

How It Works

When i = 1 (odd), k starts at 1 and prints once. When i = 2 (even), k starts at 2 and prints 2 then 4. When i = 3, k runs 1, 3, 5 as 1 3 5, and so on as row width grows. print() after the inner loop starts the next row.

📈 User Input

Read the row count at runtime with input().

Example 2 — User Input with Conditional Expression

Read rows with input() and int() (wrap in try/except ValueError in real apps); use a compact conditional expression for k.

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

for i in range(1, rows + 1):
    k = 2 if i % 2 == 0 else 1

    for j in range(1, i + 1):
        print(k, end=" ")
        k += 2
    print()

How It Works

Same nested-loop core as Example 1; only the source of rows changes. The conditional expression 2 if i % 2 == 0 else 1 replaces the if/else block. Non-numeric input raises ValueError with bare int(input()) — use try/except for safer labs.

⚡ Flip Parity

Swap the assignment so even rows print odds and odd rows print evens.

Example 3 — Flipped Row Parity

Even rows start at 1 (odds); odd rows start at 2 (evens).

Python
rows = 5

for i in range(1, rows + 1):
    if i % 2 == 0:
        k = 1
    else:
        k = 2

    for j in range(1, i + 1):
        print(k, end=" ")
        k += 2
    print()

How It Works

Swap the if/else branches so even rows get k = 1 and odd rows get k = 2. The inner loop and k += 2 logic stay the same — only parity assignment changes.

🧠 How the Algorithm Prints Rows

1

Set up

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

Setup
2

Outer loop (row width)

for i in range(1, rows + 1) makes each row print i numbers.

Row
3

Parity + inner loop

Set k from i % 2, then print(k, end=" ") and k += 2 for i iterations.

Sequence
4

New line

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

Break
=

Alternating triangle complete

Total prints: rows(rows+1)/2O(n²) time, O(1) extra memory.

🔎 Worked Walkthrough — rows = 4

Trace each outer-loop value of i, the starting k, and the numbers printed on each row.

iParityNumbers printedRow output
1odd11
2even2, 42 4
3odd1, 3, 51 3 5
4even2, 4, 6, 82 4 6 8

Total number prints: 1 + 2 + 3 + 4 = 10 = 4×5/2.

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 j <= i 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(k, 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-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: learn i % 2 for row parity first; compare with flipped assignment in Example 3.

Usage Tips

Small habits that keep number-pattern code clean.

  1. 1. Name Bounds Clearly

    Use rows (or n) and reset k at the start of each outer-loop iteration.

  2. 2. Prefer try/except ValueError

    Wrap int(input()) in try/except ValueError so bad input does not leave rows 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, start k, and each k += 2 step before coding.

  5. 5. Dry-Run One Small n

    Trace rows = 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 alternating odd/even 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(k, end=" ") for numbers; print() only after the inner loop.

  2. 2. Forgetting to Reset k

    Reusing k from the previous row mixes odd and even sequences.

    → Set k from i % 2 at the start of each outer-loop iteration.

  3. 3. Using k += 1 Instead of k += 2

    k += 1 mixes odd and even numbers within the same row.

    → After each print, update with k += 2 to keep parity.

  4. 4. Forgetting the Row Break

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

    → Always end the row after the inner loop.

  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.

rows = 1

Single digit

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.

Large n

Many rows

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

Bad input

Non-numeric input

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

k += 1

Wrong step on k

k += 1 mixes odd and even — use k += 2 within each row.

Stale k

Forgot to reset k

Set k fresh each row from i % 2 — do not carry over from the previous row.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Left-shifted odd triangle

2. Fill-with-5 triangle

  • Ascending sequence then pad with n
  • Continue with Program 19

3. Flip row parity

  • Swap odd/even row assignment
  • 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

  • Triangular sum. Total prints = rows(rows+1)/2 — O(n²) for n rows.
  • print(k, end=" ") stays on the line; print() advances — mix them carefully.
  • Validate rows > 0 for interactive programs; rows = 1 should print a single 1.
  • This page is left-aligned. Centered pyramids need leading spaces — covered later in the series.

Quick Takeaway: outer loop grows row width, set k from i % 2, print k then k += 2, then break the line.

⏱️ Time and Space Complexity

ProgramTimeExtra space
Nested loops (Examples 1–2)O(rows²)O(1)
Flip parity (Example 3)O(rows²)O(1)
Wrap Up

🎉 Conclusion

The alternating odd/even number triangle is a compact lesson in row parity: i % 2 picks the start value, and k += 2 keeps each row odd-only or even-only. Master the if/else version, then try the conditional-expression and flip-parity variants.

Practice the three examples above, then continue to Program 19 for the fill-with-5 number triangle.

Reset k each row from i % 2 — use k += 2 inside the inner loop and validate rows when reading input.

💡 Best Practices

✅ Do

  • Explain i % 2 row parity before coding
  • Use print(k, end=" ") and reset k each row
  • Validate rows ≥ 1 for interactive programs
  • Wrap int(input()) in try/except ValueError before using rows
  • State O(n²) time when asked about complexity

❌ Don’t

  • Call print() inside the inner digit loop
  • Use k += 1 instead of k += 2 within a row
  • Forget to reset k at the start of each row
  • Skip the newline after each row
  • 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 pattern

Print the pattern the beginner-friendly way.

5
Core concepts
02

Start k

1 for odd rows, 2 for even

Code
% 03

k += 2

Stays odd or even

Code
04

Grow width

Row i prints i nums

Shape
O 05

Complexity

O(n²) time

Analysis

❓ Frequently Asked Questions

We check i % 2. If i is odd, set k = 1 for odd numbers; if i is even, set k = 2 for even numbers.
Row 2 is even, so k starts at 2. The inner loop prints k then adds 2 twice: 2, then 4.
print(k, end=" ") stays on the same line with a trailing space. print() ends the current line. Numbers use end=" "; the row break uses print() after the inner loop.
Row 3 is odd, so k starts at 1 and increments by 2 three times: 1, 3, 5.
After printing k, update k += 2 so the sequence stays odd or even while increasing.
Yes. Change the odd-row start from 1 to 3 and keep k += 2 to stay in the odd sequence.
Yes. Swap the condition so even rows start at 1 and odd rows start at 2 — see Example 3.
O(n²) for n rows. Total digit prints equal n+(n-1)+…+1 = 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.
The outer loop never runs, so nothing is printed. Validate and prompt again if you want a clear user message.

Did you Know? 🔊

Row parity picks the start value: odd rows begin at 1, even rows at 2. Then k += 2 keeps each row odd-only or even-only — still O(n²) total prints for n rows.

Continue to Program 19

Move on to the fill-with-5 number triangle in the Python number-pattern series.

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