如何修复 TypeError: 'int' object is not iterable? [英] How do I fix TypeError: 'int' object is not iterable?

查看:663
本文介绍了如何修复 TypeError: 'int' object is not iterable?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,允许您输入班级中的学生人数,然后为每个学生输入 3 个测试成绩来计算平均值.我是编程新手,我不断收到一个错误,我不明白它的含义或如何解决它.这是我目前所拥有的:

students=int(input('请输入班级学生人数:'))学生人数:first_grade=(input("请输入学生的一年级:"))second_grade=(input("请输入学生的二年级:"))third_grade=(input("请输入学生的三年级:"))

解决方案

当你写作时

学生人数:

您的意图是,运行这段代码 students 次,其中 students 是我刚刚输入的值."但是在 Python 中,你传递给 a for 语句 需要是某种可迭代对象.在这种情况下,您想要的只是一个 range 声明.这将生成一个数字列表,遍历这些将允许您的 for 循环执行正确的次数:

范围内的人数(学生):# 做东西

在幕后,range 只是生成一个序列号列表:

<预><代码>>>>范围(5)[0, 1, 2, 3, 4]

就您而言,数字是多少并不重要;以下两个 for 语句会做同样的事情:

对于范围内的数字(5):对于 [1, 3, 97, 4, -32768] 中的数字:

但使用 range 版本被认为更惯用,如果您需要更改循环中的某种列表(这可能是您稍后需要做的),则更方便.

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: "))

解决方案

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

这篇关于如何修复 TypeError: 'int' object is not iterable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆