在输入的数字之前打印完美正方形的所有值

时间:2017-02-07 01:57:51

标签: python loops

number = int(input("Please enter a positive number? "))
if number >= 0:
    for i in range(1, number + 1):
        perfect_squares = i**2
        print(perfect_squares, end=" ")
elif number < 0:
    print("Error: you entered a negative number")

如果我输入数字10,例如,我希望它输出“1 4 9”,它现在输出从1到10的所有完美正方形。

如何结束循环只能将数字输出到输入的数字?

2 个答案:

答案 0 :(得分:0)

只需将范围更改为在用户输入的数字的平方根处停止:

number = int(input("Please enter a positive number? "))
if number >= 0:
    for i in range(1, int(number ** 0.5 + 1)):
        perfect_squares = i**2
        print(perfect_squares, end=" ")
elif number < 0:
    print("Error: you entered a negative number")

输出:

Please enter a positive number? 10
1 4 9 

答案 1 :(得分:0)

试试这个

number = int(input("Please enter a positive number? "))
if number >= 0:
for i in range(1, number + 1):
    perfect_squares = i**2
    print(perfect_squares, end=" ")
    if perfect_squares > i:  # add if statement here
        break
elif number < 0:
    print("Error: you entered a negative number")