Python - TypeError:“NoneType”对象不可迭代
Posted
技术标签:
【中文标题】Python - TypeError:“NoneType”对象不可迭代【英文标题】:Python - TypeError: 'NoneType' object is not iterable 【发布时间】:2017-08-29 01:58:38 【问题描述】:我试图阻止输入除整数以外的任何平均值作为平均值,但我不断收到 TypeError 的 Traceback。下面是我的程序,以及尝试输入除 int 以外的任何内容作为平均值时的程序输出:
grades_file = open('grades.txt', 'w')
def get_averages():
student = 1
for i in range(3):
name, average = get_name_average()
student += 1
grades_file = open('grades.txt', 'a')
grades_file.write("Student Name: " + name + '\n' + "Student Average: " + str(average) + '\n\n')
grades_file.close()
print(("Added %s's average of %i to the file 'grades.txt. You are now entering information for student %i of 12.") % (name, average, student))
def get_name_average():
student_name = input("Please enter the student's name: ")
try:
student_average = int(input(("Please enter the average for %s: ") % student_name))
verified_average = check_grade_input(student_average)
return student_name, verified_average
except ValueError:
print("ERROR!! Please enter grade value as an integer!")
except TypeError:
print('Type error too!')
def check_grade_input(average):
legal_input = False
while not legal_input:
if (average < 0):
print("Nah bro, invalid number...")
average = int(input("Please enter another average that is above 0: "))
elif (average > 100):
print("Nah bro, invalid number...")
average = int(input("Please enter another average that is below 100: "))
else:
return average
def show_grades_file():
grades_file = open('grades.txt', 'r')
grade_contents = grades_file.read()
grades_file.close()
print("\nThe information you entered for into file 'grades.txt' is:\n\n" + grade_contents)
def main():
get_averages()
show_grades_file()
main()
回溯和输入:
Please enter the student's name: Aaron
Please enter the average for Aaron: as
ERROR!! Please enter grade value as an integer!
Traceback (most recent call last):
File "Documents/ProgrammingFundamentals/Lab6/aaron_blakey_Lab6b.py", line 52, in <module>
main()
File "Documents/ProgrammingFundamentals/Lab6/aaron_blakey_Lab6b.py", line 49, in main
get_averages()
File "Documents/ProgrammingFundamentals/Lab6/aaron_blakey_Lab6b.py", line 13, in get_averages
name, average = get_name_average()
TypeError: 'NoneType' object is not iterable
【问题讨论】:
【参考方案1】:在函数 get_name_average 中,您在异常部分打印了消息 print("ERROR!! Please enter grade value as an integer!"),但您没有返回任何值.
默认情况下,系统将返回无值和必需的两个值名称、平均值。
您需要遵循以下代码。
def get_name_average():
student_name = input("Please enter the student's name: ")
try:
student_average = int(input(("Please enter the average for %s: ") % student_name))
verified_average = check_grade_input(student_average)
return student_name, verified_average
except ValueError:
print("ERROR!! Please enter grade value as an integer!")
return False,False
except TypeError:
print('Type error too!')
return False,False
之后,如果您遇到异常,则 name,average=False,False。
在get_averages函数中,如果名称为False,则需要添加一个条件,则系统不应写入文件。
这可能会对你有所帮助。
【讨论】:
以上是关于Python - TypeError:“NoneType”对象不可迭代的主要内容,如果未能解决你的问题,请参考以下文章