Display Multiplication Table in Python

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

What You’ll Learn

A times table is a short loop: for each row index i, print base x i = base * i. This tutorial covers fixed and interactive bases, a custom row limit, a live preview, worked Python examples, edge cases, and complexity.

Definition

Times table

Rows of products for one base number.

For Loop

range(1, last+1)

Repeat the same print pattern for each row.

Format

base x i =

Clear f-string rows that match school tables.

Input

Validate n

Read a positive integer and reject bad text.

Live Preview

Any base

Print rows 1–10 for a base you choose.

O(k) Cost

O(1) space

Linear in the number of printed rows.

Introduction

A multiplication table for a base n is the list of products n×1, n×2, … up to some limit (often 10). In code, that is a single loop that prints one formatted row per multiplier.

Interviews use this to check loops, f-strings, and simple input validation — not fancy math. Once the helper exists, you can swap a fixed base for user input or change how many rows you print.

Why it matters?

It is one of the cleanest ways to show you understand for loops, range, and readable console output.

Key Highlights

One Loop

Each i prints one product row.

Helper First

Reuse print_multiplication_table.

Validate Input

Catch non-integers and non-positive bases.

Flexible Limit

Pass last as 10, 12, or 20.

In short: for i from 1 to last, print base x i = base * i.

📝 Problem & Approach

Given a base number and a row limit, print each product from 1 through that limit in a readable format.

python
# base = 5, last = 10
# 5 x 1 = 5
# 5 x 2 = 10
# ...
# 5 x 10 = 50

Inputs & Outputs

ItemTypeDescription
baseintThe number whose table you print (often positive).
lastintHow many rows to print (commonly 10).
OutputtextOne line per row: base x i = product.

Minimal workflow

Pseudocode
procedure print_table(base, last):
    print heading
    for i from 1 to last:
        print base, i, and base * i

Method comparison

MethodIdeaNotes
for + rangeKnown row countInterview default — clearest
whileIncrement a counterWorks; slightly more boilerplate
Hard-coded printsTen separate linesAvoid — does not scale with last

⚡ Quick Reference

GoalPattern
Loop rowsfor i in range(1, last + 1):
Print rowprint(f"{base} x {i} = {base * i}")
Fixed demobase = 5, last = 10
Read basen = int(input(...).strip())
Reject bad inputexcept ValueError / if n <= 0
Align columnsf"{i:2}", f"{base * i:4}"

📋 for vs while vs Hand Prints

Same table — different ways to drive the rows.

for + range
for i in range(...)

This page — clearest for fixed counts

while
i = 1; while i <= last

Fine alternate; remember to increment

Hard-coded
10 print lines

Breaks as soon as last changes

Interview tip
helper(base, last)

Reusable function beats one-off scripts

Context

When This Problem Shows Up

Reach for a times-table loop whenever you need repeated formatted product rows.

  1. Beginner loop drills

    First programs that combine range and print.

  2. School / lab assignments

    Print the table for a number the user types.

  3. f-string practice

    Build readable rows with interpolation.

  4. Input validation warm-ups

    Handle ValueError and non-positive bases.

  5. Not a full grid

    One base only — nested loops are a different problem.

Key benefit: a tiny reusable helper that teaches loops, formatting, and validation in one place.

🔮 Live Preview

Default base is 5 to match Example 1. Change it and click Print table.

Prints rows from 1 to 10. Enter a whole number.

Live result
Press “Print table”.

Examples Gallery

Three complete Python programs — fixed table for 5, user-entered base, and a custom row limit with a while loop. Click View Output to reveal sample console results.

📚 Getting Started

A reusable helper and the classic 5-times table.

Example 1 — Table for 5 (Fixed Base)

Classic 5-times table from 1 to 10.

python
def print_multiplication_table(base: int, last: int) -> None:
    print(f"Multiplication table for {base}:")
    for i in range(1, last + 1):
        print(f"{base} x {i} = {base * i}")


def main() -> None:
    base = 5
    last = 10
    print_multiplication_table(base, last)


if __name__ == "__main__":
    main()

How It Works

range(1, last + 1) produces multipliers 1 through 10. Each iteration prints one formatted product line for base 5.

⚡ Interactive Input

Read a positive integer and print its table up to 10.

Example 2 — Table for a Number You Type

Reads a positive integer and prints its table up to 10.

python
def print_multiplication_table(base: int, last: int) -> None:
    print(f"Multiplication table for {base}:")
    for i in range(1, last + 1):
        print(f"{base} x {i} = {base * i}")


def main() -> None:
    try:
        n = int(input("Enter a positive integer: ").strip())
    except ValueError:
        print("Could not read an integer.")
        return

    if n <= 0:
        print("Please enter a positive integer.")
        return

    print_multiplication_table(n, 10)


if __name__ == "__main__":
    main()

How It Works

Conversion errors become a clear message via except ValueError. Non-positive values are rejected before printing, matching typical school-table rules.

⚙️ Flexible Limits

Let the caller choose how many rows to print — here with a while loop.

Example 3 — Custom Last Row With while

Prints the 7-times table through 12 using a while counter.

python
def print_multiplication_table_while(base: int, last: int) -> None:
    print(f"Multiplication table for {base} (up to {last}):")
    i = 1
    while i <= last:
        print(f"{base} x {i} = {base * i}")
        i += 1


def main() -> None:
    print_multiplication_table_while(7, 12)


if __name__ == "__main__":
    main()

How It Works

A while loop needs an explicit counter and i += 1 each pass. Prefer for + range when the row count is known; use while when the stop condition is more open-ended.

🧠 How the Algorithm Prints the Table

1

Choose base & last

Fix them in code or read them from input.

Setup
2

Loop i = 1..last

Walk each multiplier in order.

Loop
3

Compute product

product = base * i for the current row.

Math
=

Print the row

Output base x i = product, then continue.

🔎 Worked Walkthrough — Table of 5

Trace the first few rows for base = 5, last = 10.

ibase * iPrinted row
155 x 1 = 5
2105 x 2 = 10
3155 x 3 = 15
same pattern
10505 x 10 = 50

After i = 10, the loop ends — matching Example 1.

Use Cases

Where printing a times table shows up beyond the interview prompt.

1. Loop Warm-Ups

First clean for-loop with range.

Example: table of 5.

2. Lab Assignments

User types a base; you print 1–10.

Example: Example 2 flow.

3. Formatting Drills

Practice f-strings and alignment.

Example: width fields.

4. Validation Practice

Reject text and non-positive bases.

Example: try / except.

5. Teaching for vs while

Same output, two loop styles.

Example: Example 3.

6. Bridge to Factorial

Another loop that multiplies repeatedly.

Example: related topic.

Pro Tip: write the helper first with fixed args, then wrap it with input — easier to debug.

Advantages

Why the loop-based table approach works well for beginners and interviews.

  1. 1. Tiny & Clear

    A few lines that anyone can dry-run on paper.

  2. 2. Scales With last

    Change 10 to 12 or 20 without rewriting prints.

  3. 3. Easy to Reuse

    One helper serves fixed demos and input programs.

  4. 4. Cheap

    O(last) time and O(1) extra memory.

Pro Tip: prefer for + range in interviews unless asked specifically for while.

Usage Tips

Small habits that keep times-table programs interview-ready.

  1. 1. Extract a Helper

    Keep printing in print_multiplication_table(base, last).

  2. 2. Use range Correctly

    Remember range(1, last + 1) is inclusive of last.

  3. 3. Validate Early

    Handle ValueError and non-positive bases before the loop.

  4. 4. Parameterize last

    Do not hard-code 10 inside the helper if assignments vary.

  5. 5. Align When Needed

    Use width fields for neat columns in demos.

Pro Tip: dry-run 5×1 through 5×3 aloud — if those rows match, the loop is correct.

Common Pitfalls

Mistakes that commonly break times-table programs.

  1. 1. Off-by-One range

    Using range(1, last) and missing the last row.

    → Use range(1, last + 1).

  2. 2. Forgotten while Increment

    Infinite loop when i never increases.

    → Always i += 1 inside while.

  3. 3. Uncaught ValueError

    Calling int() on non-numeric text crashes.

    → Wrap input conversion in try / except.

  4. 4. Ten Hard-Coded Prints

    Copy-pasted lines that cannot change last.

    → Always use a loop.

  5. 5. Confusing With Full Grid

    Nesting loops when only one base was asked.

    → One loop for one times table.

Edge Cases

Handle these before claiming the table program is complete.

Input

Non-integer text

Catch conversion errors and show a clear message.

Base

Zero or negative base

Decide whether to allow or reject based on assignment rules.

Last

last < 1

Loop prints nothing — validate if that is unexpected.

Large

Very large last

Still O(last); output volume grows with rows.

Zero

Base 0

Products are all 0; math works, school rules may reject it.

Neg

Negative base

Products flip sign; allow only if the problem says so.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • School convention. Many curricula stop at 10 or 12; parameterize last either way.
  • One loop is enough. A full multiplication grid needs nested loops; one base does not.
  • Related to factorial. Factorial also multiplies in a loop, but accumulates a product instead of printing rows.
  • Formatting is free. Alignment does not change asymptotic cost — only readability.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Reproduce table of 5

  • Match Example 1 output exactly
  • Use a helper with last=10

2. Add input validation

  • Reject non-integers
  • Reject n <= 0

3. Custom last

  • Ask for base and last
  • Print through that limit

4. while version

  • Rewrite Example 1 with while
  • Do not forget i += 1

Notes

  • Core loop: print base * i for each row index.
  • Cost: linear in the number of printed rows.
  • Extension: take both base and row limit from user input.
  • You can align outputs with fixed-width formatting. Let users choose last row (10, 12, 20) if the assignment asks.

Quick Takeaway: loop i from 1 to last, print base x i = base * i, validate input when needed.

⏱️ Time and Space Complexity

TaskTimeExtra space
Print last rowsO(last)O(1)
Input + printO(last)O(1)
while versionO(last)O(1)

Ignoring the size of printed text, cost grows with how many rows you emit.

Wrap Up

🎉 Conclusion

A multiplication table is a short loop that prints base x i = base * i for each multiplier. Prefer a reusable helper, validate interactive input, and parameterize last when assignments ask for 12 or 20 rows.

Practice the three examples above, then continue to checking whether a number is a natural number.

for i in range(1, last + 1): print f"{base} x {i} = {base * i}".

💡 Best Practices

✅ Do

  • Use a helper with base and last
  • Prefer for + range
  • Validate interactive input
  • Print clear base x i = rows
  • State O(last) time / O(1) space

❌ Don’t

  • Hard-code ten print lines
  • Forget last + 1 in range
  • Skip ValueError handling
  • Forget i += 1 in while
  • Nest loops for one base

Key Takeaways

Knowledge Unlocked

Five things to remember about multiplication tables

Print a times table the interview-friendly way.

5
Core concepts
f 02

Format

base x i =

Output
? 03

Input

Validate n

Safety
n 04

last

Parameterize rows

Flexible
O 05

Cost

O(last) / O(1)

Analysis

❓ Frequently Asked Questions

It is a list of products like n x 1, n x 2, and so on. Each row is one multiplication.
Because the same pattern repeats for each row. Only the counter changes.
School tables often use 1 to 10. You can change the upper limit to 12 or any positive number.
Yes. A while loop works too, but for is simpler when the number of rows is known.
Multiplication still works, but classic school tables usually use positive bases. You can validate input and reject non-positive values if needed.
If you print k rows, time is O(k) and extra space is O(1), ignoring output text.
Use f-string width fields such as {i:2} or {product:4} so numbers line up in columns.
Often yes for assignments. Keep a reusable print_multiplication_table(base, last) helper either way.
Not for one times table. Nested loops appear when you print many bases at once (full grid).

Did you Know? 🔊

A multiplication table for a number n is the list n x 1, n x 2, .... A loop prints these rows automatically instead of writing each line by hand.

Continue to Natural Number

Learn how to check whether a number is a natural number in Python.

Natural number 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.

8 people found this page helpful