for x in range(0,501):
m = x ** 2
if m > 500:
break
print (m,x)
#this outputs a value for the highest square that is above 500 when I want the highest that is below 500
CodePudding user response:
The problem is you are breaking the loop once the value for m
has already exceeded 500. So when you try to print the value for m
it is the value that is above 500.
A solution would be to use the value of x
and because we know that the desired value would be one less than this, we can compute m
like so:
for x in range(501):
m = x ** 2
if m > 500:
break
x -= 1
print(x**2, x)
CodePudding user response:
Yet another approach:
n = 0
for x in range(500):
m, n = n, (x 1) ** 2
if n > 500:
break
print(m, x) # 484 22
CodePudding user response:
Your code assigns the value of m
before breaking, so it stores that value before breaking.
Try this instead:
for x in range(0, 501):
if (x 1) ** 2 > 500:
m = x ** 2
break
print(x, m)
Notes
Since you're new and it sounds like you're still learning about coding, I will add a few pointers.
First, you don't need to assign value to x
to test the value of a function applied to it. Second, a better approach would be to use a while
loop rather than a for
loop, like this:
x = 0
while (x 1) ** 2 < 500:
x = x 1
print(x, x**2)
Additionally, loops are slow, brute force ways to write code. Sometimes that's okay or necessary, but when there's a very efficient way to solve a problem without a loop, it's usually better to use it. For example, to find the smallest integer whose square is less than or equal to x, we can use:
import math
def int_root(x):
return int(math.sqrt(x))
int_root(500)
CodePudding user response:
As mentioned by others the issue with your code is that when you check to see if m is greater than 500, if m is exceeding 500 the program breaks the loop, the catch is that m has already been given the value that is over 500 and as such prints that out instead of the desired one before. To counteract this we can add to x and square the result to see if that answer is over 500 and if it is the program will break.
def squareless(top):
for x in range(0, top):
if (x 1) ** 2 > top 1:
m = x ** 2
print(x, m)
break
squareless(500)
CodePudding user response:
You break the loop after m
already exceeds 500
, so (529, 23)
is expected. Note that 23 ** 2 = 529
. You want to retreat to the previous x
and previous m
in this case.
for x in range(0,501):
m = x ** 2
if m > 500:
x -= 1
m = x ** 2
break
print (m,x) # 484 22
Or check the next x
to break before exceeding 500:
for x in range(0,501):
m = x ** 2
if (x 1) ** 2 > 500:
break