Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (50.2k points)

I want to create a program that will take a user-inputted integer and I want to convert it into its Roman numeral equivalent. What I have so far is:

Screenshot of my code:


I'm struggling with the main program. 

Right now my code doesn't even print anything.

1 Answer

0 votes
by (108k points)
edited by

You can deal with the problem with the help of the divmod function. You can check if the provided number matches any Roman numeral from the highest to the lowest. At every match, you should return the corresponding character.

You can use an OrderedDict so that you can iterate "downwards" the list, then I use a recursion of divmod to generate matches. Eventually, you can join all the generated answers to produce a string.

from collections import OrderedDict

def write_roman(num):

    roman = OrderedDict()

    roman[1000] = "M"

    roman[900] = "CM"

    roman[500] = "D"

    roman[400] = "CD"

    roman[100] = "C"

    roman[90] = "XC"

    roman[50] = "L"

    roman[40] = "XL"

    roman[10] = "X"

    roman[9] = "IX"

    roman[5] = "V"

    roman[4] = "IV"

    roman[1] = "I"

    def roman_num(num):

        for r in roman.keys():

            x, y = divmod(num, r)

            yield roman[r] * x

            num -= (r * x)

            if num <= 0:


    return "".join([a for a in roman_num(num)])

Taking it for a spin:

num = 35

print write_roman(num)


num = 994

print write_roman(num)


num = 1995

print write_roman(num)


num = 2015

print write_roman(num)


For more information regarding the same, do refer to the Python online course that will help you out in a better way. 

If you want to know more about Python basics then do refer to the below Python tutorial:

Related questions

Browse Categories