python返回后无法获取值

2022-05-21 06:57:12 发布

您现在位置:Python中文网/ 问答频道 /正文

a=input("give me the integer")
result=""
def int_to_roman(a):

    if type(a) != type(1):
      raise TypeError, "expected integer, got %s" % type(a)
    if not 0 < a < 1000000:
      raise ValueError, "Argument must be between 1 and 1000000"
      ints = (1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,   5,  4,   1)
      nums = ('M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
      result=""
    for i in range(len(ints)):
      result=""
      count = int(a / ints[i])
      result += nums[i] * count
      a -= ints[i] * count
      return result
      print("the result is " + result)

伙计们,它说最终的结果是不确定的,有人能解释我做错了什么吗


Tags: thetoinputifdeftypecountintegerresultintmeraisenumsgiveints
2条回答
网友
1楼 ·

您必须取消第二个if语句中返回后的行的缩进

if type(a) != type(1):
  raise TypeError, "expected integer, got %s" % type(a)
if not 0 < a < 1000000:
  raise ValueError, "Argument must be between 1 and 1000000"
ints = (1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,   5,  4,   1)
nums = ('M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
result=""
for i in range(len(ints)):
  result=""
  count = int(a / ints[i])
  result += nums[i] * count
  a -= ints[i] * count
print("the result is " + result)
return result

希望这有帮助

网友
2楼 ·

假设我对代码的缩进方式是正确的,并且省略了实际调用函数的一行,那么问题是不允许在不声明全局变量的情况下修改函数范围中的全局变量。因此,如果您希望能够在函数执行后读取result,只需将global result添加到函数的顶部

不过,这通常是个糟糕的想法—— 只需将函数的结果赋给一个值就更好了,比如

result = int_to_roman(a)
print(result)