Reputation: 63
So i'm writing a code, listing square numbers lower than n. I want the output to be a list. like so: [1, 4, 9, 16] etc.
n=int(input("input number: "))
counter = 1
while counter * counter < n:
for counter in range(1,n):
a = counter*counter
print (a)
if a < n:
break
I would be very grateful if I can get some help.
Upvotes: 1
Views: 31
Reputation: 12199
you can remove the need for the while
loop and utilise pythons range
function to generate your numbers up to n
and use a for
loop to iterate over them. you also need to initalise a list
to store them in before the loop starts. and then each iteration of the loop append the square number to the list.
n=int(input("input number: "))
squares = []
for num in range(1, n):
squares.append(num * num)
print(squares)
OUTPUT for n=10
[1, 4, 9, 16, 25, 36, 49, 64, 81]
Although this can be simpfied using pythons list comprehension style as
n=int(input("input number: "))
squares = [num * num for num in range(1, n)]
print(squares)
OUTPUT for n=10
[1, 4, 9, 16, 25, 36, 49, 64, 81]
UPDATE based on comment from B. Go
user B. Go pointed out that my answer is printing all the results of squaring number up to the value of N. But the question was actually print all the square numbers less than N. Below code to print squares less than N
n=int(input("input number: "))
squares = []
for num in range(1, n):
result = num * num
if result >= n:
break
squares.append(num * num)
print(squares)
OUTPUT N=50
[1, 4, 9, 16, 25, 36, 49]
Upvotes: 2