You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中KeyError问题求助:新手登录系统代码报错

解决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] to users_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 \n ensures 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.txt file to verify existing user credentials

内容的提问来源于stack exchange,提问作者Prasanna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 10:27:26