只打印if中的第二个命令,如果输入为十进制,则不会输出第一个命令。我检查了2个代码分开,他们工作完美。我只想打印十进制,如果它的罗马和罗马,如果它的十进制
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)
答案 0 :(得分:0)
你的行
if numberchk==int :
似乎不正确。你应该使用
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)
可以在以下代码中找到if为false的原因
a = 3
b = ( a == int)
c = type (a)
d = type(int)
print a, b, c, d
输出: 3,False,(类型'int')(类型'type')
这是因为您正在尝试测试值。如果你真的想如图所示测试它,它应该是
type(a) == int:
但是,在您的代码类型(numberchk)中会返回“str”,因为您还没有转换它。这就是为什么你必须使用try:except:method。