0

I've tried the following Python 3 code that transform from Roman to Integer.

The code is working fine. But there is a problem happened when I input an integer number or string (ex: 1, 2 or any integer number, string) it shows the message "Invalid input! Try again!" and the program ends. I want if the program input is valid it will end but if the input is invalid the input message should continue till its become a valid input.

Here is my code:

class Solution(object):
   def roman_to_int(self, s):
      """
      :type s: str
      :rtype: int
      """
      roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
      i = 0
      num = 0
      while i < len(s):
         if i+1<len(s) and s[i:i+2] in roman:
            num+=roman[s[i:i+2]]
            i+=2
         else:
            #print(i)
            num+=roman[s[i]]
            i+=1
      return num
ob1 = Solution()

message = str(input("Please enter your roman number: "))
try:
    n = ob1.roman_to_int(message)
    if n > 3999: raise Exception()
    print(n)
except Exception:
    print("Invalid input! Try again!")
code_program
  • 33
  • 1
  • 6

1 Answers1

1

Try this:

while True:
    message = input("Please enter your roman number: ")
    try:
        n = ob1.roman_to_int(message)
        if n > 3999: raise Exception()
        print(n)
        break
    except Exception:
        print("Invalid input! Try again!")
I'mahdi
  • 23,382
  • 5
  • 22
  • 30