Python中KeyError问题求助:新手登录系统代码报错
Hey there! Let's break down why you're seeing that KeyError and get your account creation code working smoothly.
问题根源
Take a look at these lines in your account creation block:
users_entry['name'] = users_entry[name] users_entry['email'] = users_entry[email] users_entry['password'] = users_entry[password]
You’ve got the assignment backwards! Right now, you’re trying to read a value from your empty users_entry dictionary using the user’s input (like their name string) as a key—but since the dictionary starts completely empty, those keys don’t exist at all. That’s exactly why you’re hitting the KeyError.
What you actually want to do is write the user’s input values to the dictionary keys ('name', 'email', 'password').
修复后的代码
Here’s the corrected version of your code, plus a few small tweaks for readability:
import pprint users_entry = {} account = input("Do you already have an account? (Y/N): ").lower() if account == 'y': print("Happy logging in!") else: acc_creation = input("Would you want to create an account? (Y/N): ").lower() if acc_creation == 'y': name = input("Please provide us with your name: ") email = input("Please enter your email Id: ") password = input("Enter your password: ") confirm = input("Confirm your password: ") if password == confirm: # Fix: Assign user input values to dictionary keys directly users_entry['name'] = name users_entry['email'] = email users_entry['password'] = password print("Woo-hoo! Your account has been created!") else: print("Please check your password again") # Write the user data to the file (added newline for cleaner entries) with open('user.txt','a') as user_list: user_list.write(pprint.pformat(users_entry) + '\n')
关键修改说明
- Fixed dictionary assignment: Changed
users_entry['name'] = users_entry[name]tousers_entry['name'] = name—this takes the user’s input value and stores it under the correct key in the dictionary. - Simplified input handling: Combined the input prompt and
.lower()conversion into one line to keep the code cleaner. - Added newline between entries: Appending
\nensures each user’s data is on its own line in the text file, making it easier to read or parse later.
额外小建议
If you plan to expand this system down the line, consider:
- Adding basic email format validation (to ensure users enter a valid email address)
- Hashing passwords instead of storing them in plain text (raw password storage is a big security risk!)
- Adding login logic that reads the
user.txtfile to verify existing user credentials
内容的提问来源于stack exchange,提问作者Prasanna

