roman /decimal calculator error with if command
本问题已经有最佳答案,请猛点这里访问。
它只打印if中的第二个命令,如果输入是十进制的,则不会生成第一个命令。我把这两个代码分开检查,它们工作得很好。我只想打印十进制,如果是罗马的,如果是十进制的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | 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 (" The roman numeral", roman,"is equal to",number) |
你行
1 | if numberchk==int : |
似乎不正确。你应该使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | 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 (" The roman numeral", romanval,"is equal to", decval) |
if为false的原因可以在以下代码中找到
1 2 3 4 5 | a = 3 b = ( a == int) c = type (a) d = type(int) print a, b, c, d |
输出:3,false,(类型"int")(类型"type")
这是因为您试图测试这些值。如果你真的想如图所示测试这个,它应该是
1 | type(a) == int: |
但是,在代码类型(numberchk)中,会返回"str",因为您尚未转换它。这就是为什么必须使用try:except:方法的原因。