I tried to add a class to this basic Roman Numeral Calculator, but when I try to run the function from the class, I get a NameError. I'm not sure what's going on.
I tried to change the order of the code, but nothing else as I don't know what the reason for the error is.
Also, I don't know why but I can't get the class (below) part into the code block.
class Roman_Number():
roman_numeral_table = [
("M", 1000), ("CM", 900), ("D", 500),
("CD", 400), ("C", 100), ("XC", 90),
("L", 50), ("XL", 40), ("X", 10),
("IX", 9), ("V", 5), ("IV", 4),
("I", 1)
]
r = input('If you want to go from Roman to Number, enter "1." If you want to go from Number to Roman, enter "2"')
if r == 1:
roman_to_int()
else:
int_to_roman()
def int_to_roman():
number = int(input('Provide Number: '))
if number < 1 or number > 3999:
print('Number must be inbetween 1 and 3999')
else:
print('Valid Number')
roman_numerals = []
for numeral, value in roman_numeral_table:
while value <= number:
number -= value
roman_numerals.append(numeral)
print(''.join(roman_numerals))
def roman_to_int():
pass
I expect it to start running int_to roman(), but I'm just getting an error.
I changed the order and now I'm getting a "roman_numeral_table is not defined." Why and how do I fix this?
You are getting this error, because python executes it blocks in the order of the syntax, you need to define a function before being able call it / cite it. Try this:
def roman_to_int():
pass
def int_to_roman():
number = int(input('Provide Number: '))
if number < 1 or number > 3999:
print('Number must be inbetween 1 and 3999')
else:
print('Valid Number')
class Roman_Number():
roman_numeral_table = [
("M", 1000), ("CM", 900), ("D", 500),
("CD", 400), ("C", 100), ("XC", 90),
("L", 50), ("XL", 40), ("X", 10),
("IX", 9), ("V", 5), ("IV", 4),
("I", 1)
]
r = input('If you want to go from Roman to Number, enter "1." If you want to go from Number to Roman, enter "2"')
if r == 1:
roman_to_int()
else:
int_to_roman()
roman_numerals = []
for numeral, value in roman_numeral_table:
while value <= number:
number -= value
roman_numerals.append(numeral)
print(''.join(roman_numerals))