Python Program to Convert Roman Numerals to Integers
Intermediate · Numbers
Roman numerals use letters for values: I = 1, V = 5, X = 10, L = 50, C = 100, D = 500 and M = 1000. The values are normally added, but a smaller letter placed before a bigger one is subtracted, so IV is 4 and XC is 90. This program converts a Roman numeral like MCMXCIV into the number 1994.
Program
MCMXCIV = 1994
How it works
- The dictionary
valuesmaps each Roman letter to its number. - The loop looks at each letter together with the one after it.
- If the next letter is worth more, the current letter is subtracted, as in CM = 1000 - 100; otherwise it is added.
i + 1 < len(roman)makes sure the last letter, which has nothing after it, is simply added.- For MCMXCIV that gives 1000 + 900 + 90 + 4 = 1994.
Other ways to write it
Reading from right to left
III = 3 IX = 9 LVIII = 58 MMXXVI = 2026
Going backwards, a letter is subtracted when it is smaller than the letter just after it, so there is no need to look ahead.
Integer to Roman, the other way
4 = IV 1994 = MCMXCIV 2026 = MMXXVI 3999 = MMMCMXCIX
This takes the largest value that still fits, again and again. Listing 900, 400, 90, 40, 9 and 4 as their own pairs handles the subtraction cases.
Try it yourself
Add a check that prints a friendly message when the text contains a letter that is not a Roman numeral.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises