Python 如何修复 TypeError: 'int' object is not iterable?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14941288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I fix TypeError: 'int' object is not iterable?
提问by tinydancer9454
I am trying to write a program that allows you to enter the number of students in a class, and then enter 3 test grades for each student to calculate averages. I am new to programing and I keep getting an error that I don't understand what it means or how to fix it. This is what I have so far:
我正在尝试编写一个程序,允许您输入一个班级的学生人数,然后为每个学生输入 3 个测试成绩来计算平均值。我是编程新手,我不断收到一个错误,我不明白它的含义或如何解决它。这是我到目前为止:
students=int(input('Please enter the number of students in the class: '))
for number in students:
first_grade=(input("Enter student's first grade: "))
second_grade=(input("Enter student's second grade: "))
third_grade=(input("Enter student's third grade: "))
采纳答案by bdesham
When you wrote
当你写
for number in students:
your intention was, “run this block of code studentstimes, where studentsis the value I just entered.” But in Python, the thing you pass to a forstatementneeds to be some kind of iterable object. In this case, what you want is just a rangestatement. This will generate a list of numbers, and iterating through these will allow your forloop to execute the right number of times:
你的意图是,“运行这段代码students时间,students我刚刚输入的值在哪里。” 但是在Python,你传递给事情一个for声明需求是某种迭代对象的。在这种情况下,您想要的只是一个rangestatement。这将生成一个数字列表,遍历这些将允许您的for循环执行正确的次数:
for number in range(students):
# do stuff
Under the hood, the rangejust generates a list of sequential numbers:
在引擎盖下,它range只是生成一个序列号列表:
>>> range(5)
[0, 1, 2, 3, 4]
In your case, it doesn't really matter what the numbers are; the following two forstatements would do the same thing:
在你的情况下,数字是什么并不重要;以下两个for语句会做同样的事情:
for number in range(5):
for number in [1, 3, 97, 4, -32768]:
But using the rangeversion is considered more idiomatic and is more convenient if you need to alter some kind of list in your loop (which is probably what you're going to need to do later).
但是,range如果您需要更改循环中的某种列表(这可能是您稍后需要做的事情),则使用该版本被认为更惯用,并且更方便。
回答by eagleflo
Numbers can't be iterated over. What you're probably looking for is the rangefunction, which will create a sequence of numbers up to the number you want:
数字不能重复。您可能正在寻找的是range函数,它将创建一个数字序列,直到您想要的数字:
for number in range(1, students + 1):
for number in range(1, students + 1):
The reason I added + 1 there is because the second argument to range is exclusive.
我在那里添加 + 1 的原因是因为 range 的第二个参数是独占的。
回答by Adiraamruta
try this...it will work...
试试这个……它会起作用……
i=0
x = "abcd"
print("Using for loop printing string characters")
for i in range(len(x)):
print(x[i])

