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

后端 未结 3 1569
孤街浪徒
孤街浪徒 2020-11-30 13:01

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

相关标签:
3条回答
  • 2020-11-30 13:02

    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).

    0 讨论(0)
  • 2020-11-30 13:16

    Numbers can't be iterated over. What you're probably looking for is the range function, which will create a sequence of numbers up to the number you want:

    for number in range(1, students + 1):

    The reason I added + 1 there is because the second argument to range is exclusive.

    0 讨论(0)
  • 2020-11-30 13:23

    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])
    
    0 讨论(0)
提交回复
热议问题