无法在Python中为非平方整数编码

如何创建一个代码,打印出所有小于 100 且不是任何整数的平方的整数?

例如,不打印 3^2=9,但应该打印 30。

我已经设法打印出平方值,但不确定如何打印出不是正方形的值。

这是我的代码:

for i in range(1,100):
    square = i**2

    print(square)

回答

您可以通过多种方式编写此代码。我认为你可以在这里使用两个for循环来让你更容易。我正在使用评论,以便您作为新手更好地理解。您可以从这两个中选择您认为更容易理解的一个:

list_of_squares = []               #list to store the squares
              
for i in range(1, 11):             #since we know 10's square is 100 and we only need numbers less than that
    square = i ** 2
    list_of_squares.append(square) #'append' keeps adding each number's square to this list
    
for i in range(1, 100):
    if i not in list_of_squares:   #'not in' selects only those numbers that are not in the squares' list
        print(i)

或者

list_of_squares = []

for i in range(1, 100):
    square = i ** 2
    list_of_squares.append(square)
    if square >= 100:              #since we only need numbers less than 100
        break                      #'break' breaks the loop when square reaches a value greater than or equal to 100
        
for i in range(1, 100):
    if i not in list_of_squares:
        print(i)


以上是无法在Python中为非平方整数编码的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>