Astonishing Astonishing -4 years ago 108
Python Question

Output squares using a while loop

Im trying to accomplish taking an input number, for ex 8 and have it output all of the squares up to 64. so 1,4,9,16,25,36,49,64. I want to do it without using the exponent operator. I have run into a problem where my loop is just jumping straight to 64 and skipping the other squares.

limit = input('Enter a value for limit: ')
limit = int(limit)
square= (limit)*(limit)
ctr = 1
while ctr <= (limit):
print(ctr, end=' ')
ctr = (square) + 1
print("limit =", square )

Answer Source

Your counter(ctr) increment part is wrong. When you do ctr = (square) + 1, you are making it more then the limit in the first iteration itself. For example, lets say the limit is 8, which means square is 64.

Now you want your loop to run while ctr is less than equal to limit.

You start with ctr=1 and then in the first iteration itself, its updated to ctr = 64 + 1. That's the problem.

The loop counter as per your requirement should increment by 1. So you need to change it to ctr = ctr +1 or ctr += 1.

And you need to print ctr*ctr instead of just ctr as you want squares.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download