Skip to content
Advertisement

Roman Numeral to Integer with User Input

Roman numeral to integer converter with user input. I got this code below:

roman_numerals = {"I" : 1,
                  "V" : 5,
                  "X" : 10,
                  "L" : 50,
                  "C" : 100,
                  "D" : 500,
                  "M" : 1000
                  }

int_value = 0

user_input = input("Enter Roman Number: ").upper()

for i in range(len(user_input)):
    if user_input[i] in roman_numerals:
            if i + 1 < len(user_input) and roman_numerals[user_input[i]] < roman_numerals[user_input[i + 1]]:
                int_value -= roman_numerals[user_input[i]]
            else:
                int_value += roman_numerals[user_input[i]]
            print("The integer value is: ", int_value)
    else:
        print("Invalid input.")

The problem is, it prints the string “The integer value is: ” the same count as the len(user_input) wherein it should only show one line of this string. For example, user inputs ‘XIX’ which is converted as ’19’ in decimal, the output goes like:

The integer value is: 10
The integer value is: 9
The integer value is: 19

I would really appreciate your feedbacks to it as I am new to python and I want to grow and improve in it.

Advertisement

Answer

You have to move your print out of the loop. Like this

roman_numerals = {"I" : 1,
                  "V" : 5,
                  "X" : 10,
                  "L" : 50,
                  "C" : 100,
                  "D" : 500,
                  "M" : 1000
                  }

int_value = 0

user_input = input("Enter Roman Number: ").upper()

for i in range(len(user_input)):
    if user_input[i] in roman_numerals:
        if i + 1 < len(user_input) and roman_numerals[user_input[i]] < roman_numerals[user_input[i + 1]]:
            int_value -= roman_numerals[user_input[i]]
        else:
            int_value += roman_numerals[user_input[i]]
    else:
        print("Invalid input.")
        quit()

print("The integer value is: ", int_value)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement