如果用词写出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语句变为false时,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
有相同的问题。小于10的数字不返回
Base10
。BiggerThan20
不会返回数字> = 40。关于python - TypeError:+不支持的操作数类型:“int”和“NoneType”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21820664/