Check Perfect Square in Python

Beginner
⏱️ 9 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Number Theory

What You’ll Learn

A perfect square equals k * k for some whole number k. Examples: 1, 4, 9, 16, 25. This tutorial covers the loop and math.isqrt approaches, a live checker, worked Python examples, edge cases, and complexity.

Definition

n = k²

Some integer k squares to n.

i*i Loop

Beginner

Try candidates while i*i <= n.

math.isqrt

Robust

Integer root, then root*root == n.

0 and 1

Both square

0*0 and 1*1 both count.

Live Preview

Try 16 / 15

See k and the verdict instantly.

Not Perfect Number

Different idea

Squares vs divisor sums.

Introduction

A perfect square is a non-negative integer that equals some integer squared. So 16 is perfect because 4 * 4 = 16, while 15 is not because no whole k works.

Interviews usually accept either a clear i * i loop or a math.isqrt check. Prefer integer roots over floating sqrt so large values stay exact.

Why it matters?

It is a classic math interview warm-up that teaches exact integer reasoning without float traps.

Key Highlights

n = k²

Some integer k squares to n.

Two Methods

Loop or math.isqrt.

0 and 1

Both are perfect squares.

Avoid Float

isqrt beats float sqrt.

In short: find whether some integer k satisfies k * k == n.

📝 Problem & Approach

Given an integer n, decide whether it is a perfect square of a non-negative integer.

python
# 16 -> 4 * 4 = 16   perfect
# 15 -> no integer k  not perfect
# 0  -> 0 * 0 = 0    perfect
# 1  -> 1 * 1 = 1    perfect

Inputs & Outputs

ItemTypeDescription
n / numberintValue to test (non-negative for yes).
ReturnboolTrue when some k has k*k == n.
Optional kintThe integer root when the answer is yes.

Minimal workflow

Pseudocode
function is_perfect_square_loop(n):
    if n < 0:
        return false
    i = 0
    while i * i <= n:
        if i * i == n:
            return true
        i = i + 1
    return false

Method comparison

MethodIdeaNotes
i*i loopTry candidates until square exceeds nClearest for beginners
math.isqrtroot = isqrt(n); root*root == nFast and exact for integers
float sqrtround(sqrt(n))**2 == nRisky for large n — avoid

⚡ Quick Reference

GoalPattern
Reject negativesif n < 0: return False
Loop checkwhile i * i <= n:
Exact hitif i * i == n: return True
isqrt checkroot = math.isqrt(n)
Verify rootreturn root * root == n
Build squaresk * k for k = 0, 1, 2, …

📋 Loop vs isqrt vs Float

Same question — different reliability.

i*i loop
while i*i <= n

Interview-friendly and exact

math.isqrt
root*root == n

Preferred production check

float sqrt
avoid for ints

Rounding can lie on big n

vs perfect number
k*k vs s(n)=n

Different “perfect” meaning

Context

When This Problem Shows Up

Reach for a square check whenever you need exact integer roots.

  1. Interview warm-ups

    Simple math with an exactness twist.

  2. Grid / geometry puzzles

    Can n form a square layout?

  3. Filtering sequences

    Keep only square values in a range.

  4. Teaching isqrt

    Show why integer roots beat floats.

  5. Not for float domains

    This tutorial targets integer n.

Key benefit: one crisp boolean question that forces you to think in exact integers, not approximate roots.

🔮 Live Preview

Checks with integer logic, then reports the root and verdict.

Use whole numbers n >= 0.

Live result
Press “Run check” to see result.

Examples Gallery

Three complete Python programs — loop check for 16, list squares from 1 to 50 with math.isqrt, and generate squares by squaring. Click View Output to reveal sample console results.

📚 Getting Started

A beginner-friendly loop that never needs floating roots.

Example 1 — Integer Loop Check

Simple and beginner-friendly perfect square check.

python
def is_perfect_square(number: int) -> bool:
    if number < 0:
        return False
    i = 0
    while i * i <= number:
        if i * i == number:
            return True
        i += 1
    return False


test_number = 16
if is_perfect_square(test_number):
    print(f"{test_number} is a perfect square.")
else:
    print(f"{test_number} is not a perfect square.")

How It Works

Candidates advance from 0 while i * i has not passed 16. When i reaches 4, the product matches and the function returns True.

⚡ Integer Square Root

Use the standard library for a crisp, exact check.

Example 2 — Range Scan Using math.isqrt

Use math.isqrt and print all perfect squares from 1 to 50.

python
import math


def is_perfect_square(num: int) -> bool:
    if num < 0:
        return False
    root = math.isqrt(num)
    return root * root == num


print("Perfect Squares in the Range 1 to 50:")
for i in range(1, 51):
    if is_perfect_square(i):
        print(i, end=" ")

How It Works

math.isqrt(num) returns the floor of the square root. Squaring that root recovers num exactly when num is a perfect square.

Example 3 — Generate Squares by Squaring

Build squares directly instead of filtering every integer.

python
print("First squares from k = 0 to 7:")
for k in range(0, 8):
    square = k * k
    print(f"{k} * {k} = {square}")

How It Works

When you only need the square sequence, squaring consecutive integers is cheaper than testing every n in a range.

🧠 How the Algorithm Decides

1

Reject negatives

No non-negative integer squares to a negative.

Guard
2

Find a candidate root

Loop i while i*i <= n, or call isqrt(n).

Search
3

Compare square to n

Exact match means perfect square.

Rule
=

Return the verdict

True with root k, or False.

🔎 Worked Walkthrough — 16

Trace the loop method for n = 16.

ii * ii*i <= 16?Match?
00YesNo
11YesNo
24YesNo
39YesNo
416YesYes — return True

4 * 4 equals 16 — perfect square.

Use Cases

Where perfect-square checks show up beyond the interview prompt.

1. Interview Classics

Exact integer math checks.

Example: is_square(16).

2. Range Filtering

List squares inside a band.

Example: 1..50 list.

3. Sequence Generation

Build squares with k*k.

Example: Example 3.

4. Grid Layouts

Can n tiles form a square?

Example: 25 -> 5×5.

5. Teaching isqrt

Show exact integer roots.

Example: avoid float sqrt.

6. Next: Averages

Continue the interview chain.

Example: related CTA.

Pro Tip: say “I’ll check whether root*root equals n using an integer root” before coding.

Advantages

Why these approaches work well for beginners and interviews.

  1. 1. Easy to Trace

    Dry-run 16 on paper and watch i grow.

  2. 2. Exact Integers

    No float rounding surprises with isqrt.

  3. 3. Two Clear Styles

    Loop for clarity; isqrt for speed.

  4. 4. Generates Cleanly

    k*k builds the sequence without scanning.

Pro Tip: lead with the loop in interviews, then mention math.isqrt as the robust alternative.

Usage Tips

Small habits that keep square checks interview-ready.

  1. 1. Guard Negatives

    Return False immediately for n < 0.

  2. 2. Prefer isqrt

    Exact integer root for production code.

  3. 3. Verify root*root

    Never trust a root without squaring back.

  4. 4. Generate When Possible

    Use k*k if you need the sequence itself.

  5. 5. Separate From Perfect Number

    Name the definition so interviewers know you know.

Pro Tip: sanity-check 0, 1, 16, and 15 — if those four behave, your logic is solid.

Common Pitfalls

Mistakes that commonly break perfect-square programs.

  1. 1. Trusting float sqrt

    Large ints can round incorrectly.

    → Use math.isqrt or an integer loop.

  2. 2. Skipping root verification

    Taking floor(sqrt) without squaring back.

    → Always compare root * root to n.

  3. 3. Confusing With Perfect Number

    Different “perfect” concept entirely.

    → This page is about k * k.

  4. 4. Forgetting 0

    Starting i at 1 and rejecting zero.

    → 0 = 0 * 0 is a square.

  5. 5. Accepting Negatives

    Returning True for -16 in real-integer checks.

    → Reject n < 0 in this tutorial.

Edge Cases

Handle these before claiming the check is complete.

n = 0

Zero is square

0 = 0 * 0.

n = 1

One is square

1 = 1 * 1.

Negative

Not a real integer square

Return false for negatives in this tutorial.

Large n

Avoid float precision

Prefer math.isqrt over float sqrt.

15

Classic no

Between 9 and 16 — not square.

16

Classic yes

4 * 4 = 16.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Odd gaps. Differences between consecutive squares are odd: 3, 5, 7, 9…
  • Grid picture. n tiles form a square if and only if n is a perfect square.
  • isqrt identity. Perfect ⇔ isqrt(n)² == n for n >= 0.
  • Name clash. Perfect square ≠ perfect number.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Prove 16

  • Trace the loop
  • Confirm 4 * 4

2. Reject 15

  • Show no matching i
  • isqrt(15)=3, 9 != 15

3. List 1..50

  • Reproduce Example 2
  • Expect seven values

4. Generate k*k

  • Print first eight squares
  • Match Example 3

Notes

  • Definition: n is square if n = k * k.
  • Methods: integer loop or math.isqrt.
  • Remember: 0 and 1 are perfect squares.
  • Prefer math.isqrt over float sqrt. The loop approach takes O(sqrt(n)) checks. Return false immediately for negatives.

Quick Takeaway: n is a perfect square when some integer k satisfies k * k == n.

⏱️ Time and Space Complexity

ApproachTime (single n)Extra space
Loop until i*i > nO(sqrt(n))O(1)
isqrt-based checkO(1) practicalO(1)
Range 1..U scanO(U) checksO(1)

For interview demos, either method is fine; mention float pitfalls when asked about reliability.

Wrap Up

🎉 Conclusion

A perfect square equals some integer squared. Use an i * i loop or math.isqrt, reject negatives, and remember that 0 and 1 count.

Practice the three examples above, then continue to finding the average of N numbers.

n = k² means perfect square; verify with integers, not float sqrt.

💡 Best Practices

✅ Do

  • Reject negatives early
  • Verify root * root == n
  • Prefer math.isqrt for exactness
  • Treat 0 and 1 as squares
  • Generate with k*k when listing

❌ Don’t

  • Trust float sqrt alone
  • Skip squaring the root back
  • Confuse with perfect numbers
  • Forget zero as a square
  • Accept negatives as yes

Key Takeaways

Knowledge Unlocked

Five things to remember about perfect squares

Decide exact squares the interview-friendly way.

5
Core concepts
i 02

Loop

while i*i

Method
03

isqrt

root*root

Robust
0 04

Edges

0, 1 yes

Guards
O 05

Cost

O(√n)

Analysis

❓ Frequently Asked Questions

A whole number is a perfect square if it equals k * k for some whole number k.
Yes. 1 = 1 * 1.
The loop is easy to understand and avoids floating-point concerns.
It means we only test candidate roots whose square has not passed n.
Yes. It gives exact integer square root and is great for robust checks.
No. Perfect square is about k * k; perfect number is about divisor sums.
Yes. 0 = 0 * 0.
Large integers can round incorrectly; math.isqrt stays exact for integers.
About O(sqrt(n)) candidate checks for a single n.

Did you Know? 🔊

A perfect square can be arranged into a square grid with equal rows and columns. The gaps between consecutive squares (1, 4, 9, 16...) are odd numbers (3, 5, 7, 9...).

Continue to Average of N Numbers

Learn how to find the average of N numbers in Python.

Average 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.

9 people found this page helpful