0

My program should have a single input where you write either an arabic number, a roman number, or adding roman numbers. For example:

Year: 2001
... MMI

Year: LX
... 60

Year: MI + CI + I
... MCIII

Year: ABC
... That's not a correct roman numeral

Well, I guess you get the deal. First, I tried with something like this:

def main():


    year = input ("Year: ")


    if type(int(year)) == type(1):
        arab_to_rome(year)

    else:
        rome_to_arab(year)
main()

This have obvious problems, firstly, everything else than an integer will be considered as roman numerals and it doesn't take addition in consideration.

Then I googled and found something called isinstance. This is the result of trying that:

def main(input):

    year = input ("Year: ")


    if isinstance(input,int):
        arab_to_rome(year)

    elif isinstance(input,str):
        rome_to_arab (year)
    else:
        print ("Error")
main()

This has problems as well. I get an error message stating: Invalid syntax. This code doesn't take addition in consideration either.

Knells
  • 827
  • 2
  • 12
  • 24
Lackdemnono
  • 33
  • 1
  • 4

1 Answers1

0

You can use a try/except block to see if the input is an int. This makes up the first 3 lines of the code. For more on that see this question.

year = input('Year: ')
try:
   print(arab_to_rome(int(year)))
except ValueError:
   result = 0
   for numeral in year.split('+'):
       numeral.replace(' ','')
       result += rome_to_arab(numeral)
   print(result)

The part after the except is a simple way to handle the addition, and you could migrate this into your rome_to_arab function if you wish. It splits the string on each + and then add the result of the Arabic calculations together to make a complete Arabic result. The replace() function gets rid of any extra spaces to make sure it doesn't break your other methods. See this question or more info on split() and replace().

As you haven't shown us the conversion methods I'm going to assume arab_to_rome returns a string and rome_to_arab returns an int. If not you should probably change them such that they do (not just for my example, but for good code convention)

Community
  • 1
  • 1
Knells
  • 827
  • 2
  • 12
  • 24