我尝试了下面的Python 3代码,从罗马转换到整数。
代码一眼就能正常工作。但是,当我输入一个整数或字符串(例如:1,2或任何整数,字符串)时,会出现某些问题,它会显示一些代码错误。我想当我输入任何东西,除了罗马数字(1到3999),它应该返回"重试"
下面是我的代码:class Solution(object):
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
roman = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000,'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900}
i = 0
num = 0
while i < len(s):
if i+1<len(s) and s[i:i+2] in roman:
num+=roman[s[i:i+2]]
i+=2
else:
#print(i)
num+=roman[s[i]]
i+=1
return num
ob1 = Solution()
message = str(input("Please enter your roman number: "))
if (ob1.romanToInt(message)) <= 3999:
print (ob1.romanToInt(message))
else:
print ("Try again")
试试这个:
message = str(input("Please enter your roman number: "))
try:
n = ob1.romanToInt(message)
if n > 3999: raise Exception()
print(n)
except Exception:
print("Try again")