2016-11-29 87 views
0

如何迭代字典並在迭代循環期間檢查輸入值的有效性?這個問題在代碼中描述:如何迭代字典並檢查輸入的有效性?

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? 

回答

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') 
+2

我想補充一個try /除用於'ValueError'用戶輸入一個非數字。 –

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 
1

可以interate剛過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 
0

要完成此任務,只需使用continue關鍵字即可。 問題是你正在用盡字典。

解決方案:

  1. mydict = { '堪薩斯':0, '達拉斯':0, '阿拉巴馬':0}

    爲鍵,在mydict.items值():INP = -1 而(INP = INT(輸入( '您的數目:' +鍵))== 0){通過}

    if inp > 0: 
        value = inp