How to convert an integer to Roman numerals in Python

1 Answer

0 votes
def int_to_roman(num: int) -> str:
    # Define values and their corresponding Roman numerals
    values = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
    symbols = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]

    roman = []

    # Loop through values and subtract while possible
    for value, symbol in zip(values, symbols):
        while num >= value:
            num -= value
            roman.append(symbol)

    return "".join(roman)


if __name__ == "__main__":
    print(int_to_roman(1994))  
    print(int_to_roman(196))   
    print(int_to_roman(9))     




'''
run:

MCMXCIV
CXCVI
IX

'''

 



answered Nov 2, 2021 by avibootz
edited Dec 1, 2025 by avibootz
...