我试图阻止输入平均值以外的任何整数,但我一直收到TypeError的Traceback。下面是我的程序,以及尝试输入平均值以外的任何东西时的程序输出:
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
答案 0 :(得分:2)
在功能 get_name_average 中,您在例外部分打印(“错误!!请输入等级值作为整数!”)中打印消息,并且您没有返回任何值
默认情况下,系统将不返回任何值&amp;需要两个值名称,平均值。
您需要遵循以下代码。
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
之后如果你有异常,那么名字,average = False,False。
在函数 get_averages 中,如果name为False,则需要添加一个条件,然后系统不应该在文件中写入。
这可能会对你有帮助。