Roman Numeral to Integer with User Input

Question:

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.

Asked By: SoulSeeker916

||

Answers:

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)
Answered By: Pw Wolf
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.