visit
The most common scenario where developers get this error is when you try to iterate a number using for loop where you tend to forget to use the range()
method, which creates a sequence of a number to iterate.
students=int(input('Please enter the number of students in the class: '))
for number in students:
math_grade=(input("Enter student's Maths grade: "))
science_grade=(input("Enter student's Science grade: "))
social_grade=(input("Enter student's Scoial grade: "))
# Output
Please enter the number of students in the class: 5
Traceback (most recent call last):
File "c:\Projects\Tryouts\listindexerror.py", line 3, in <module>
for number in students:
TypeError: 'int' object is not iterable
The easier way everyone thinks here is to go with for loop and iterate the number of students to accept the grade. If you run the code, Python will throw a TypeError: ‘int’ object is not iterable.
In Python, unlike lists, integers are not directly iterable as they hold a single integer value and do not contain the **‘__iter__
‘ ** method; that’s why you get a TypeError.
print(dir(int))
print(dir(list))
print(dir(dict))
If you look at the output screenshots, int does not have the ** ‘'
'
** method.
The second approach is: if you still want to iterate int object, then try using the range()
method in the for loop, which will eventually generate a list of sequential numbers.
students=int(input('Please enter the number of students in the class: '))
for number in range(students):
math_grade=(input("Enter student's Maths grade: "))
science_grade=(input("Enter student's Science grade: "))
social_grade=(input("Enter student's Scoial grade: "))
The post appeared first on .