TypeError:不支持+:'NoneType'和'str'/Base转换的操作数类型

2024-10-03 11:16:44 发布

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

这是我的代码,我只是不明白这个代码不工作。你知道吗

def theBase(n, b):
   convertString = "0123456789"
   if n < b:
      return convertString[n]
   else:
      return toBase(n//b,b) + convertString[n%b]

def toBase(n, b):
   print(theBase(n, b), end="")

def main():
    n = int(input())
    b = int(input())
    print(n, "in base", b, "is ", end="")
    toBase(n, b)
if __name__ == "__main__":
    main()

不修改主功能


Tags: 代码ininputbasereturnifmaindef
1条回答
网友
1楼 · 发布于 2024-10-03 11:16:44

出现此问题的原因是函数toBase()返回None,因为没有显式的返回语句。然后函数theBase()中的最后一行尝试将来自toBase()(无)的返回值添加到字符串中,这将给出您看到的异常。你知道吗

我认为您有一个简单的错误,theBase()应该调用自身,而不是toBase()(请参阅该函数的最后一行)。以下操作将解决此问题:

def theBase(n, b):
   convertString = "0123456789"
   if n < b:
      return convertString[n]
   else:
      return theBase(n//b,b) + convertString[n%b]

相关问题 更多 >