python - 向/从字典错误添加和报告数据
问题描述
程序让用户输入一个州缩写,然后是大写。
如果字典已经包含用户输入的州,那么它需要报告它的首都,同时继续循环让用户输入州和他们的首都。
我的问题是我无法弄清楚如何让程序报告资本然后继续循环。它只是无限地打印状态和资本。
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('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
,它也会在之后请求另一个状态,并且它不会陷入无限循环。
结果:
推荐阅读
- google-apps-script - 在 Google 表格中,是否可以将活动单元格的内容显示到另一个单元格?
- android - android studio Arctic Fox 2021.3.1 在gradle bar 中不显示#signing 报告| #SHA1 未显示问题已解决
- javascript - 无法将单击事件添加到在创建对象之前未创建的按钮
- .net - .net 5 在启动中将 AutoSaveChanges 设置为 false
- github - 如何在 GutHub 中分配来自不同团队的不同数量的 Pull Request 审阅者
- algorithm - 在 O(m) 时间内使用非邻接表检查图的连通性
- apache-kafka-streams - Kafka Streams 转换方法和流时间戳
- go - ERC-20 代币转移问题:执行恢复:ERC20:从零地址转移
- python - super() 的返回类的不可见属性(继承)
- python - 如何只初始化其中一个对象