Convert Integer to Roman using Recursion in Python

Write a program that includes a recursive function in Python which takes one integer as input and returns the Roman equivalent of that number.

Hint: The following are the various symbols used in Roman Number System:
I is for 1
V is for 5
X is for 10
L is for 50
C is for 100
D is for 500
M is for 1000

There is no symbol for 0 in Roman Number System.
Using the same symbol for more than three times in a row is not permitted.

def convert(num):
    if num > 3999 or num <= 0:
        return ""
    if num >= 1000:
        return "M" + convert(num - 1000)
    if num >= 900:
        return "CM" + convert(num - 900)
    if num >= 500:
        return "D" + convert(num - 500)
    if num >= 400:
        return "CD" + convert(num - 400)
    if num >= 100:
        return "C" + convert(num - 100)
    if num >= 90:
        return "XC" + convert(num - 90)
    if num >= 50:
        return "L" + convert(num - 50)
    if num >= 40:
        return "XL" + convert(num - 40)
    if num >= 10:
        return "X" + convert(num - 10)
    if num >= 9:
        return "IX" + convert(num - 10)
    if num >= 5:
        return "V" + convert(num - 5)
    if num >= 4:
        return "IV" + convert(num - 4)
    if num >= 1:
        return "I" + convert(num - 1)

num = int(input("Enter the number: "))
if num >3999 or num <= 0:
    print("Number out of range!")
else:
    roman = convert(num)
    print(roman)

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.