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

Python中while循环内用户输入值无法正确添加到字典的问题

问题分析与解决

问题根源

你的代码逻辑里,else分支的执行顺序错了:先通过add_state = input(...)更新了变量,再往字典里存值。当你输入CA、输入首府后直接回车退出时,add_state被赋值为空字符串,导致字典用空字符串作为键存储了首府,原本要添加的CA直接被丢弃了。

修正方案

调整else分支的代码顺序,先把当前的州缩写(也就是用户刚输入的add_state)和对应首府存入字典,再去获取下一次的输入。

修正后的代码

states = {'ID': 'Boise', 'VT': 'Montpelier', 'SD': 'Pierre', 'ND': 'Bismark'}
add_state = input('Enter state abrev. or Enter to quit ')
while add_state != '':
    if add_state in states:
        print(f'Already have {add_state}, capital {states[add_state]}')
        add_state = input('Enter state abrev. or Enter to quit ')
    else:
        capital = input(f'Enter capital of {add_state} ')
        # 先保存当前州缩写和首府
        states[add_state] = capital
        # 再获取下一轮输入
        add_state = input('Enter state abrev. or Enter to quit ')
print(states)

测试结果

运行后按示例输入:

Enter state abrev. or Enter to quit CA
Enter capital of CA sacramento
Enter state abrev. or Enter to quit 

输出的字典会正确包含CA:

{'ID': 'Boise', 'VT': 'Montpelier', 'SD': 'Pierre', 'ND': 'Bismark', 'CA': 'sacramento'}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 00:47:07