'Finding nearest square in python using - for loop [duplicate]

I wrote a program to find the nearest square in python using while loop, which goes like the below:

num = 0
while (num+1)**2 < limit:
    num += 1
nearest_square = num**2
print(nearest_square)

This made me wonder, if we can find the same using a for loop. I am unable to understand how can we set the range of the same.

Can anyone please guide?



Solution 1:[1]

This is probably the best way to find the nearest square.

int(limit ** (0.5)) ** 2

If limit = 200 then the output is 196.

But if you want to do the exact same thing you did above using for loop use this,

for num in range(limit + 1):
  if (num + 1) ** 2 >= limit:
    break

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zero