Python程序报错:'int' object does not support item assignment 求助
解决你的Python成绩统计程序报错问题
Hey there! Let's fix that TypeError you're running into. The root cause here is variable name collision—you're using the same name m for two completely different things: your student dictionary and the math marks input, which breaks the code later on.
What's going wrong exactly:
- You start by defining
m = {}(an empty dictionary meant to store student names and their total marks). - Later, you run
m = int(input('enter students marks in maths:'))—this overwrites the dictionarymwith an integer value (the math score you just input). - When you try to do
m[a] = tafterward, Python throws an error because you're trying to treat an integer like a dictionary. Integers can't have key-value pairs assigned to them, which is why you see theTypeError: 'int' object does not support item assignmentmessage.
Fixed & Cleaned-up Code
Here's the corrected version with a unique variable name for math marks, plus some tweaks for readability and proper syntax (your original print statements had broken line breaks that could cause issues):
print('Welcome to the student marklist program') def display_student_results(student_dict): for name, total_marks in student_dict.items(): if total_marks > 60: print(f'Student {name} has got a total of {total_marks} marks and passed with distinction.') elif total_marks > 40: print(f'Student {name} has got a total of {total_marks} marks and passed with first class.') elif total_marks > 20: print(f'Student {name} has got a total of {total_marks} marks and passed with second class.') else: print(f'Student {name} has got a total of {total_marks} marks and failed the exam.') student_records = {} while True: student_name = input("Enter student's name: ") # Use a unique variable name for math marks to avoid overwriting the dictionary math_marks = int(input("Enter student's marks in maths: ")) chem_marks = int(input("Enter student's marks in chemistry: ")) phys_marks = int(input("Enter student's marks in physics: ")) cs_marks = int(input("Enter student's marks in computer science: ")) total = math_marks + chem_marks + phys_marks + cs_marks student_records[student_name] = total add_another = input('Want to add another student? Enter yes or no: ').lower() if add_another != "yes": break display_student_results(student_records)
Quick Tips for Your Future Coding:
- Use descriptive variable names (like
student_recordsinstead ofm,math_marksinstead ofm)—this makes your code easier to read and avoids silly name collision mistakes. - Add input validation (e.g., check if the user enters a valid number for marks) to handle invalid inputs gracefully instead of crashing.
- Keep lines of code concise to avoid accidental line-break syntax errors.
内容的提问来源于stack exchange,提问作者Ram Pandey
相关产品推荐
相关产品推荐

