如何迭代字典并在迭代循环期间检查输入值的有效性?问题在代码中描述:
mydict ={'Kansas': 0, 'Dallas': 0, 'Alabama': 0}
for key, value in mydict.items():
inp = int(input('Your number for: ' + key))
if inp > 0:
value = inp
else:
print('enter again') #<---how can I jump back to the key
# for which the entry was false
# and ask again for the entry?
答案 0 :(得分:2)
for key, value in mydict.items():
while True:
try:
inp = int(input('Your number for: ' + key))
except:
inp = 0
if inp > 0:
mydict[keu] = inp
break
print('enter again')
答案 1 :(得分:1)
mydict ={'Kansas': 0, 'Dallas': 0, 'Alabama': 0}
for key, value in mydict.items():
inp = int(input('Your number for: ' + key))
while inp <= 0:
inp = int(input('Enter again for: ' + key))
value = inp
答案 2 :(得分:1)
如果keys
,您可以在items
上进行互动。请尝试以下代码:
my_dict = {'Kansas': 0, 'Dallas': 0, 'Alabama': 0}
for key in my_dict.keys():
inp = int(input('Your number for: {} '.format(key)))
while inp <= 0:
inp = int(input('Your number for: {} '.format(key)))
my_dict[key] = inp
答案 3 :(得分:0)
要完成此操作,只需使用continue关键字即可。 问题是你正在用尽字典。
解决方案:
mydict = {'堪萨斯':0,'达拉斯':0,'阿拉巴马':0}
表示密钥,mydict.items()中的值:inp = -1 while(inp = int(输入('你的数字为:'+键))== 0){pass}
if inp > 0:
value = inp