Search code examples
pythonwhile-loopsquare

Nearest Square Function with Python - why is my solution is incorrect


I was told to post a new question - refer to post : Nearest Square Function with Python

objective is as find largest nearest square to limit = 40.

I came up with a solution but I didn't understand why this doesn't work. Correct outcome would be printing the numbers up to 36, not exceeding 40.

limit = 40 #given limit by quiz 
num=0 #set point by me 
square=num*num #this is what a square means #it could also be said of num**2 

while square<limit:
    square=num**2
    num=num+1
    print((num-1),square)

result i would get is :

1 1
2 4
3 9
4 16
5 25
6 36
7 49

why does the line 7 square 49 appear ?


Solution

  • It is beacause you are checking square < limit and when the number = 6 the suare = 25 which satisfies the condition and the line 6 36 is printed next the number turns 7 andsqure turns 36 which is still less then 40 therefore it prints 7 49 and increments the number to 8 and now when the program checks for the while condition it fails as 49 < 40 == False therefore the program execution stops. you could modify your code as:

        limit = 40    # given limit by quiz 
        num = 1    # start with 1 as 0 suare is 0 and is not required by you i guess
        while (num * num) < limit:
            print((num),(num * num))    # prints num and square of num
            num += 1        # increments num by 1
    

    Output:

        1 1
        2 4
        3 9
        4 16
        5 25
        6 36