Python中的平方数列 [英] Square number sequence in Python
问题描述
我是 python 新手,我正在尝试编写代码来打印所有平方数,直到用户输入的所需值的平方为止.
I'm new to python and I am trying to make a code to print all the square numbers until the square of the desired value entered by the user.
n = raw_input("Enter number")
a = 1
while a < n:
a = 1
print(a*a)
a += 1
if a > n:
break
当我运行此代码时,它会无限打印1";...我猜 a
的值不会增加 +=
所以它永远是 a=1
.我该如何解决这个问题?
When I run this code it infinitely prints "1" ... I'm guessing that the value of a
does not increase by +=
so it's a=1
forever. How do I fix this?
推荐答案
存在一些问题.首先,您的输入(raw_input()
返回的内容)是一个字符串,因此您必须将其转换为整数:
There are some problems. First, your input (what raw_input()
returns) is a string, so you must convert it to integer:
n = int(raw_input(...))
其次,您在每次迭代中都设置 a = 1
,因此,由于循环条件是 a <n
,循环将永远运行(如果 n > 1
).您应该删除该行
Second, you are setting a = 1
each iteration, so, since the loop condition is a < n
, the loop will run forever ( if n > 1
). You should delete the line
a = 1
最后,没有必要检查 a >n
,因为循环条件会处理它:
Finally, it's not necesary to check if a > n
, because the loop condition will handle it:
while a < n:
print a * a
a += 1
# 'if' is not necessary
这篇关于Python中的平方数列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!