Python program to convert numbers into roman numerals

Roman numerals Python Converter

Instructions

Python challenge to create a Roman numerals converter. Your task is to write a Python script that converts figures, requested and entered by the user, to Roman numerals. It is a fantastic Python exercise to practice dictionaries and loops.

  1. The program should take user input for the figure to be converted.
  2. Implement the conversion algorithm using one of the three methods described below.
  3. Display the Roman numeral equivalent of the input figure.

Roman numerals are a numeral system that originated in ancient Rome and were used widely throughout the Roman Empire. Instead of using a positional system like the modern decimal system (0-9), Roman numerals use a combination of letters to represent numbers. The basic symbols in the Roman numeral system are:

  • I: 1
  • V: 5
  • X: 10
  • L: 50
  • C: 100
  • D: 500
  • M: 1000

To represent larger numbers, the symbols are combined. For example, the number 6 is represented as “VI” (5 + 1), and the number 14 is represented as “XIV” (10 + 1 + 1 + 1)

Steps

  1. Create a dictionary that maps each Roman numeral to its corresponding decimal value.
  2. Initialize an empty string variable to store the Roman numeral.
  3. Take user input for the figure to be converted.
  4. Compare the input figure with the base values in descending order.
  5. Divide the input figure by the base value and repeat the process until the input figure becomes zero.
  6. For each division, append the corresponding Roman symbol to the result string.
  7. Display the result string as the Roman numeral equivalent of the input figure.

Expected Outcome

## Input: "Enter the figure to be converted: " 1550

## Output: Roman numeral equivalent: MDL

Python practice question source code

def convert_to_roman(num):
    roman_dict = {1000: 'M', 900: 'CM', 500: 'D', 400: 'CD', 100: 'C', 90: 'XC', 50: 'L', 40:    
    'XL', 10: 'X', 9: 'IX', 5: 'V', 4: 'IV', 1: 'I'}
    roman_num = ''
    
    for base, symbol in roman_dict.items():
        while num >= base:
            roman_num += symbol
            num -= base
    
    return roman_num

input_num = int(input("Enter the figure to be converted: "))
result = convert_to_roman(input_num)
print("Roman numeral equivalent:", result)

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart