这是我得到的错误for i in range(len(n))
:
TypeError: object of type 'int' has no len()
我在这里看过其他帖子,但还没有找到解决方案。
我糊涂了。如果您知道这里发生了什么,请发表评论。
这是我的代码:
#ch6.ex11.py
def squareEach(x):
sqrt = x*x
return sqrt
def main():
n = []
n = eval(input("Enter a list of numbers to be squared seperated by comma:\n"))
i = 1
sqrtn = ()
for i in range(len(n)):
sqrtn = squareEach(n)
++i
print("Here's your results: ",sqrtn)
main()
答案 0 :(得分:8)
n
是一个整数。你想要
for i in range(n):
答案 1 :(得分:1)
这就是我想你要做的事情:
def squareEach(x):
sqrt = x*x
return sqrt
def main():
n = list(map(int, input("Enter a list of numbers to be squared separaded by a comma").split(',')))
sqrtn = []
for i in range(len(n)):
sqrtn.append(squareEach(n[i]))
print("Here's your results: ",sqrtn)
main()
或者您可以将for循环用作:
for i in n:
sqrtn.append(squareEach(i))
或对你可以做的每个元素进行平方:
sqrtn = [x**2 for x in n]
答案 2 :(得分:1)
您似乎可能想要这样做:
def squareEach(n):
squares = []
for i in n:
squares.append(i*i)
return squares
def main():
msg = "Enter a list of numbers to be squared seperated by comma:\n"
n = list(eval(input(msg)))
sqrtn = squareEach(n)
print("Here's your results: ",sqrtn)
main()
嗯,你的代码有一些问题:
i++
在Python中无效。相当于它的Python是i += 1
。此外,Python在脚本中执行所有代码行,因此在每个Python程序中都不需要main()
函数,但在某些情况下您可能希望使用它。
你可以做的其他事情:
def main():
msg = "Enter a list of numbers to be squared seperated by comma:\n"
n = list(eval(input(msg)))
squares = [i**2 for i in n] # list comprehension
main()