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.
1# Take number2num = int(input("Enter a number: "))34# Check if perfect square5is_perfect_square = False6for i in range(0, num + 1):7 if i * i == num:8 is_perfect_square = True9 break10 if i * i > num:11 break1213if 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
Initialize the square flag false.
- 2
Try candidate roots from zero and compare i * i.
- 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.
๐Related Content
- ๐
Phase 1 - Learn Concepts
Review Phase 1 concepts and explanations
- ๐
Phase 1 - Quiz
Test your Phase 1 understanding with quiz questions
- ๐ป
Phase 1 - All Practice Problems
Explore all practice problems for Phase 1
- ๐
Master Your Logic Building - Complete Course
Browse all phases and tutorials
- ๐ง
Logic Building Overview
Learn about the complete logic building curriculum