Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

python - How do I fix TypeError: 'int' object is not iterable?

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:

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: "))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you wrote

for number in students:

your intention was, “run this block of code students times, where students is the value I just entered.” But in Python, the thing you pass to a for statement needs to be some kind of iterable object. In this case, what you want is just a range statement. This will generate a list of numbers, and iterating through these will allow your for loop to execute the right number of times:

for number in range(students):
    # do stuff

Under the hood, the range just generates a list of sequential numbers:

>>> range(5)
[0, 1, 2, 3, 4]

In your case, it doesn't really matter what the numbers are; the following two for statements would do the same thing:

for number in range(5):

for number in [1, 3, 97, 4, -32768]:

But using the range version 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...