Python: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

Python: TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

我是 Python 的初学者,我找不到下面这段代码中的错误。你知道我该如何解决吗?谢谢!

import fileinput
import time
pat = "hello"
cout = 0

with fileinput.input(files=('packet.txt')) as f:
    for line in f:
            start_time = time.time()
            val = search(txt, pat)
            end_time = time.time()
            run_time = (end_time - start_time)*1000000
            if(val == -1):
                print("No Text")
                run_time = (end_time - start_time)*1000000
                #print(" ---> Processing time: "'{0:.3f}'.format(run_time),  "microseconds")
                print(" ---> Processing time: "'{0:.3f}'.format(run_time),  "microseconds")
            else:
                val = val + 1
                print ('Pattern \"' + pat + '\" found at position',val + count)
                run_time = (end_time - start_time)*1000000
                print(" ---> Processing time: "'{0:.3f}'.format(run_time),  "microseconds")

() 中的 TypeError Traceback(最近调用最后)

     16   print(" ---> Processing time: ",'{0:.3f}'.format(run_time),  "microseconds")
     17             else:
---> 18                     val = val + 1


TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'

我怀疑你的 search() 函数 returns None 找不到模式,而不是 -1。所以改变

if val == -1:

if val is None: