2014-03-14 25 views
0

我試過把除了Keyerror:或除了例外沒有真正的工作python繼續給這個錯誤,如例如我輸入一個回溯(最近通話最後一個): KeyError異常: 'A'我想除了錯誤,如果用戶輸入一個不同的值從程序想要什麼(a,b等)

roman_to_decimal = { 'I': 1,'i':1,'v':5 , 'V': 5,'x':10, 'X': 10,'l':50, 'L': 50,'c':100, 'C': 100, \ 
         'd':500,'D': 500, 'm':1000,'M': 1000 } 
    #decimal to roman 
    def int2roman(numberdec): 
     numerals={1:"I", 4:"IV", 5:"V", 9: "IX", 10:"X", 40:"XL", 50:"L", 
        90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"} 
     result="" 
     for value, numeral in sorted(numerals.items(), reverse=True): 
      while numberdec >= value: 
       result += numeral 
       numberdec -= value 
     return result 
    while True: 
     try: 
      numberchk=(input("Enter a Roman numeral or a Decimal numeral:")) 
      break 
#the problem is here 
    except: 
     print ("Oops! That was no valid numeral. Try again...") 

回答

0
while True: 
    try: 
     numberchk = input("Enter a Roman numeral or a Decimal numeral: ") 
     if all(letter in roman_to_decimal for letter in numberchk.strip()): 
      print('doing something with roman') 
      break 
     elif numberchk.strip().isdigit(): 
      print('doing something with decimal') 
      break 
     else: 
      errmsg = "'{}' is not decimal or roman numeral.".format(numberchk) 
      raise ValueError(errmsg) # errmsg for debugging 
    except (ValueError): 
     print ("Positive decimal or roman numeral was expected. Try again...") 
相關問題