如何将for循环中所有用户输入存入文本文件?学生注册代码排查
Fix: Save All Student IDs to Your Registration File
Hey there! I see the issue with your code—let's break down what's going wrong and fix it so all student IDs get saved properly.
What's Causing the Problem?
Your current code has two key issues:
- You're overwriting the ID variable every loop: Each time you enter a new student ID, you replace the value of
id_numberinstead of storing all IDs. By the end of the loop, you only have the last ID (plus an unnecessary+1that's messing it up). - You're only writing to the file once: After the loop finishes, you write just that single (modified) ID to the file—so all previous entries are lost.
Here's the Fixed Code
Let's adjust it to store all IDs and write them all to the file:
# Get the number of students registering student_count = int(input("Please enter the amount of students registered: ")) # Create a list to hold all student IDs (so we don't overwrite them) student_ids = [] for _ in range(student_count): # Get each student's ID (we'll keep it as a string for cleaner file writing) student_id = input("Please enter student ID number: ") # Add the ID to our list student_ids.append(student_id) # Use a `with` statement to open the file—this automatically closes it when we're done with open('reg_form.txt', 'w') as reg_form: # Write the header line reg_form.write("Student ID numbers:\n") # Write each ID on its own line for readability for student_id in student_ids: reg_form.write(f"{student_id}\n") print("Thank you, ID numbers saved to reg_form.txt")
Key Improvements Explained:
- Using a list for IDs: The
student_idslist stores every ID you input, so nothing gets overwritten. - Removed the unnecessary
+1: That line was modifying the ID you entered, which isn't what you want for a registration form. withstatement for file handling: This is the safest way to work with files in Python—it ensures the file is closed properly even if something goes wrong.- Each ID on a new line: Makes the registration form easier to read when checking attendance.
Quick Test of the Fix
If you enter 3 students with IDs 123, 456, 789, your reg_form.txt will look like this:
Student ID numbers:
123
456
789
That's exactly what you need for an attendance sign-in sheet!
内容的提问来源于stack exchange,提问作者user12739323
相关产品推荐
相关产品推荐

