【问题标题】:Add and Reporting Data to/from a dictionary errors向/从字典错误添加和报告数据
【发布时间】:2021-11-24 01:09:45
【问题描述】:

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

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

我的问题是我不知道如何让程序报告回资本然后继续循环。它只是无限打印状态和资本。

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()  

【问题讨论】:

  • 您是否尝试将您的第一个 state = input (' ....') 添加到您的 while 循环中?这样您就可以重置导致无限循环的state 变量。
  • 嗨 HakunaMutata,我已经回答了问题。请看一下,期待您的回复??????????

标签: python dictionary if-statement while-loop


【解决方案1】:

只需要删除线,

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:')    # <----

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


结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-24
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多