Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Check Perfect Square

Search for an integer whose square equals the input. A beginner Python loop exercise on flags, early stopping, and why zero needs inclusion in the search.

IntermediatePhase 1 - Level 3: Math and Number LogicExample 10 of 10
check-perfect-square.py
1# Take number
2num = int(input("Enter a number: "))
3
4# Check if perfect square
5is_perfect_square = False
6for i in range(0, num + 1):
7 if i * i == num:
8 is_perfect_square = True
9 break
10 if i * i > num:
11 break
12
13if is_perfect_square:
14 print("Perfect square")
15else:
16 print("Not a perfect square")

Output

Enter a number: 16
Perfect square

Enter a number: 15
Not a perfect square

In this one

  • Track a boolean search result
  • Include root zero
  • Stop after passing the target

How it works

  1. 1

    Initialize the square flag false.

  2. 2

    Try candidate roots from zero and compare i * i.

  3. 3

    Break on equality or overshoot, then report the flag.

Edge cases

Is zero a square?

Is zero a square?

Yes. The candidate range must include root zero.

What happens for a negative input?

What happens for a negative input?

There is no nonnegative candidate root, so the result is Not a perfect square.

What's going on

A perfect square can be written as an integer times itself. The loop tries candidate roots and stores success in a boolean flag rather than printing inside every iteration.

Equality sets the flag and breaks. A square greater than the input also ends the search because later nonnegative candidates only grow. Afterward, one final branch prints the result. Zero must be a candidate because 0 * 0 equals zero.

Is zero a square? Yes. The candidate range must include root zero.

What happens for a negative input? There is no nonnegative candidate root, so the result is Not a perfect square.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why stop after i * i exceeds num?

Pick an answer to check it.

Question 2

Is zero a square?

Pick an answer to check it.

Questions people ask

Is zero a square?

Yes. The candidate range must include root zero.

What happens for a negative input?

There is no nonnegative candidate root, so the result is Not a perfect square.

Why stop after i * i exceeds num?

Later nonnegative squares will be larger too.