首页 > 解决方案 > 向/从字典错误添加和报告数据

问题描述

程序让用户输入一个州缩写,然后是大写。

如果字典已经包含用户输入的州,那么它需要报告它的首都,同时继续循环让用户输入州和他们的首都。

我的问题是我无法弄清楚如何让程序报告资本然后继续循环。它只是无限地打印状态和资本。

def main():
    
    sc=  {'FL':'Tallahassee',
          'AK':'Juneau',
          'AZ':'Phoenix',
          'CA':'Sacramento',}
    count(sc)
    print("Let's add a few more")
    state=input('Enter a States Abbreviation or Enter to quit:')
   
    while state !='':
        if state in sc:
            print(f'Already have {state}. Its Capital is',sc.get(f'{state}'))
        
        if state not in sc:
            capital=input('Enter that States Capital:')
            sc[state]=capital      
            state=input('Enter a States Abbreviation or Enter to quit:')
        

          
        
    sc_len=len(sc)
    print(f'Got {sc_len} States now. Here they are...')
    for key,value in sc.items():
        print('The capital of',key,'is',value)


main()  

标签: pythondictionaryif-statementwhile-loop

解决方案


只需要删除线,

state=input('Enter a States Abbreviation or Enter to quit:')

if-statement块中移动到while块中,如下所示:

while state !='':
        if state in sc:
            print(f'Already have {state}. Its Capital is',sc.get(f'{state}'))
        
        if state not in sc:
            capital=input('Enter that States Capital:')
            sc[state]=capital 
                 
        state=input('Enter a States Abbreviation or Enter to quit:')    # <----

现在即使state在 中sc,它也会在之后请求另一个状态,并且它不会陷入无限循环。


结果:

在此处输入图像描述


推荐阅读