I want to except the error if the user input a different value from what the programm wants ( a,b etc)
我尝试了put-except-keyror:或者exception-nothing-really work python继续给出这个错误,如果我输入了一个回溯(最近调用last):键错误:"A"
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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...") |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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...") |