-2

I am trying to go over the natural number and test each natural number if it is the perfect square print that number, but my only condition is that print only first 10 perfect square numbers.

i =2
n=1 #used for counting

while 10>=n:
        for j in range(1,i):
            x =1
            while x*x<=j:
                if x*x==j:
                    print(j)
                    n+=1
                x+=1
            i+=1
            j+=1
Raj
  • 1
  • 1
  • 3
  • 4
    What output do you get and what did you expect to get? – mkrieger1 Jun 29 '20 at 15:18
  • 3
    Welcome to StackOverflow! I see you're a new contributor, so I advise you to check out [How to ask a good question](https://stackoverflow.com/help/how-to-ask) and [How to create a minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Brian61354270 Jun 29 '20 at 15:21
  • Is there a reason you are trying to do it this way rather than just printing the squares of the first ten integers? – Mark Jun 29 '20 at 15:23
  • @MarkMeyer Because a [perfect square](https://en.wikipedia.org/wiki/Perfect_square) is something different. – Matthias Jun 29 '20 at 16:15
  • It seem that the intention of your code is to go over the natural numbers j and test each if it is a square. The test of being a square you are doing by squaring and checking if equal to j. One mistake in your code is that each time the outer `while` enters, the `j` will restart from 1 in the `for j in range(1,i)`. You can get rid of that `for`. There is already a j+=1 incrementing the `j`. – NotDijkstra Jun 29 '20 at 16:20
  • @Matthias that still seems the same to me. Can you tell me the first ten perfect squares then? – Mark Jun 29 '20 at 16:26
  • @MarkMeyer I think they are half-joking, implying that a program checking the definition would do what Raj tried to do: check each integer to see if they satisfy the definition. Namely, that there exist an integer, which square is the number. – NotDijkstra Jun 29 '20 at 16:28
  • @NotDijkstra -- maybe so, tone is hard to interpret in text. – Mark Jun 29 '20 at 17:20
  • 1
    @MarkMeyer Somehow that was an `OutOfCoffeeError` on my side. Indeed it's as simple as `print(', '.join(map(str, (i**2 for i in range(1, 11)))))`. – Matthias Jun 29 '20 at 20:00
  • @NotDijkstra you are correct I am trying to go over the natural number and test each natural number if it is perfect square print that number, but my only condition is that print only first 10 perfect square number. – Raj Jun 30 '20 at 10:18

1 Answers1

0

Perfect squares are just:

1 * 1 = 1
2 * 2 = 4
3 * 3 = 9
4 * 4 = 16
...

So you can just make a loop that goes from 1 to any int number you want (in your example it's 10), and print the square of this number like so:

for i in range(1, 11):    # it's 11 because it ranges to 11 - 1, so 10
    print(i*i)

Output:

1
4
9
16
25
36
49
64
81
100
NoeXWolf
  • 241
  • 1
  • 12