python - 类型错误:+ 不支持的操作数类型: 'int' 和 'NoneType'

标签 python bash python-2.7 typeerror

如果 1 到 x 是用单词写出的,这段未完成的代码旨在返回字母的总和:

#!/usr/bin/python
def Base1(n):
  if (n==1):
      return len('one') 
  if (n==2):
    return len('two') 
  if (n==3):
      return len('three')
  if (n==4):
      return len('four') 
  if (n==5):
      return len('five') 
  if (n==6):
      return len('six') 
  if (n==7):
      return len('seven') 
  if (n==8):
      return len('eight')
  if (n==9):
      return len('nine')
def Base10(g):
  if (g == 10):
    return len('ten')
  if (g == 11):
    return len('eleven')
  if (g == 12):
    return len('twelve')
  if (g == 13):
    return len('thirteen')
  if (g == 14):
    return len('fourteen')
  if (g == 15):
    return len('fifteen')
  if (g == 16):
    return len('sixteen')
  if (g == 17):
    return len('seventeen')
  if (g == 18):
    return len('eightteen')
  if (g == 19):
    return len('nineteen')
  if (g == 20):
    return len('twenty')
  if (g > 20):
    return BiggerThan20(g)
def BiggerThan20(t):
  if t<30:
    return len('twenty')+Base1(t-20)
  if t<40:
    return len('twenty')+Base1(t-20)


def trial(runcounter):
  summitup = 0
  if (len(str(runcounter))==1):
    summitup += Base1(runcounter)
  if (len(str(runcounter))==2):
    summitup += Base10(runcounter)
  return summitup

lettersum = 0

start = int(input("Please enter an integer: "))
for k in range(1, start+1, 1):
  lettersum += trial(k)
 #print (k, lettersum)
print(lettersum)

它运行良好直到 29,但如果我输入任何 >= 30 bash 返回以下输出:

opq@home:/home/opq/python pe17.py

Please enter an integer: 32

Traceback (most recent call last):
  File "pe17.py", line 65, in <module>
    lettersum += trial(k)
  File "pe17.py", line 58, in trial
    summitup += Base10(runcounter)
  File "pe17.py", line 45, in Base10
    return BiggerThan20(g)
  File "pe17.py", line 50, in BiggerThan20
    return len('twenty')+Base1(t-20)
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

我是编程新手,不确定为什么会出现此错误。

当 BiggerThan20 中的第一个 if 语句变为假时,Base1 似乎突然返回 None。

感谢您提供的任何帮助。

解决了! 我忘了照顾十... 谢谢你的帮助

最佳答案

Base1 不返回任何数字 10 或更大的数字。

>>> Base1(1)
3
>>> Base1(10) # None
>>> Base1(20) # None

>>> len('twenty') + Base1(10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'NoneType'

Base10, BiggerThan20 有同样的问题。

  • Base10 对于小于 10 的数字不返回。
  • BiggerThan20 不会返回数字 >= 40。

关于python - 类型错误:+ 不支持的操作数类型: 'int' 和 'NoneType',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21820664/

相关文章:

python - 异步循环 : how to implement asynio in an existing python program - and share variables/data?

Mac下的Python开发

python - 使用 Scrapy 爬取带有 JavaScript 的站点

java - Maven 无法识别 Ubuntu shell 上安装的 $JAVA_HOME jdk

python - 在 python 函数中进行分析

python - Django Blob 模型字段

linux - linux下如何使用 `find`命令删除非空目录?

linux - shell语言的数据组

在 vim 中执行的 Python 随机数列表

python - 将字符串转换为整数