Sunday, September 22, 2019

python - roman /decimal calculator error with if command




It prints only the second command in if and it doesnt make the first one if the input is decimal . i checked the 2 codes seperated and they work perfect. i just want to print decimal if its roman and roman if its decimal



roman_to_decimal = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, \
'D': 500, 'M': 1000 }
def int2roman(numberdec):
numerals={1:"I", 4:"IV", 5:"V", 9: "IX", 10:"X", 40:"XL", 50:"L",

90:"XC", 100:"C", 400:"CD", 500:"D", 900:"CM", 1000:"M"}
result=""
for value, numeral in sorted(numerals.items(), reverse=True):
while numberdec >= value:
result += numeral
numberdec -= value
return result


numberchk=(input("Enter a Roman numeral or a Decimal numeral:" ))

##here is the problem i get
if numberchk==int :
print (int2roman(int(numberchk)))
sys.exit()
else :
roman=numberchk

converted = True
number = 0


for n in range(0, len(roman)-1):
this_char = roman[n]
next_char = roman[n+1]
if (this_char in roman_to_decimal) and \
(next_char in roman_to_decimal):

this_number = roman_to_decimal[this_char]
next_number = roman_to_decimal[next_char]

if this_number < next_number:

number -= this_number
else:
number += this_number



if converted:
## add last roman numeral
number += roman_to_decimal[roman[len(roman)-1]]


print ("\nThe roman numeral", roman, "is equal to",number)

Answer



Your line



if  numberchk==int :


does not appear to be correct. You should use




try:
decval = int(numberchk)
romanval = int2roman(decval)
#Continue with other processing here
except ValueError:
# Verify that it is a legal roman numeral
romanval = numberchk
decval = roman2int(numberchk)



# Continue with your processing

print ("\nThe roman numeral", romanval, "is equal to", decval)


The reason that the if is false can be found in the following code



a = 3
b = ( a == int)
c = type (a)

d = type(int)
print a, b, c, d


OUTPUT:
3, False, (type 'int') (type 'type')



This is because you are attempting to test the values. If you really wanted to test this as shown, it should be



type(a) == int:



However, in your code type(numberchk) would return "str" because you have not yet converted it. That is why you must use the try: except: method.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...