Python Conversion Programs

Python Program To Convert An Integer To A Roman Numeral

Published March 4, 2024 by Jarvis Silva

In this tutorial we will see how to convert a integer to a roman numeral value, Integers are whole numbers like 0,1,-3, 43 etc and roman numerals are basically letters representing a number like 5 is V, 4 is VI.

So our task is to take a integer number and give output as roman numeral so let’s see how to do it.

Python code for converting integer to roman numeral

def int_to_roman(num):
    val = [
        1000, 900, 500, 400,
        100, 90, 50, 40,
        10, 9, 5, 4,
    syb = [
        "M", "CM", "D", "CD",
        "C", "XC", "L", "XL",
        "X", "IX", "V", "IV",
    roman_num = ''
    i = 0
    while num > 0:
        for _ in range(num // val[i]):
            roman_num += syb[i]
            num -= val[i]
        i += 1
    return roman_num

# Example usage:
number = int(input("Enter an integer: "))
roman_numeral = int_to_roman(number)
print(f"The Roman numeral for {number} is {roman_numeral}")

Example Ouput

Enter an integer: 10
The Roman numeral for 10 is X

Above is the complete program in python to convert a integer to roman numeral so let’s see how it works step by step:

  • The program has a function called int_to_roman to convert an integer to a Roman numeral.
  • Inside the function, lists (val and syb) hold values and symbols for Roman numerals.
  • An empty string (roman_num) is used to store the Roman numeral.
  • The program iterates through values. It subtracts the largest possible value from the input and appends the corresponding symbol to roman_num.
  • This continues until the input is zero, completing the Roman numeral.
  • The function returns the Roman numeral string.

So this was for this tutorial, I hope you found it helpful and useful, do share it with your friends who might need it, Thank you reading.