函数输出值,但返回“无”

时间:2019-09-26 07:05:53

标签: python function printing return

def findLineParam(sprotParam, pos):

    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1 
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        return line[start:stop] # returns None? 

要简要说明代码的功能,它应采用输入字符串(关键字),例如“ ID”并在文本文件中的一行上找到它,然后在读取下一个“”或“;”空格后应该找到第一个值并返回。我可以看到,当我打印该行时,它返回的正是我想要的内容,但是当我返回它时,它返回的是“无”。

每当我将“ sprotParam”更改为输入列表(* sprotParam)时,它都会返回值,但还会返回与文件中各行相对应的相等数量的“ None”,我相信这表明该行会迭代并在所有行上执行操作,而不应该执行。

调用该函数的代码

try:
    file = input("Enter filename: ")
except IOError as e:
    print("That is not a recognised filename. Error given: " + str(e)) 
    sys.exit(1) # Close the program

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2)

3 个答案:

答案 0 :(得分:1)

1不在函数范围内,因此您需要将其作为参数传递给函数:

line

更新

这是您的代码的简化版本:

def findLineParam(sprotParam, pos, line):
    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1 
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        return line[start:stop] # returns None? 

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2, line)

现在,如果您为def findLineParam(sprotParam, file): for line in file.split(sprotParam):#split by parameter if line != '<': for item in line.split(): #split by whitespace if item != '=': print(item) return item raise Exception(f'No {sprotParam} parameters were found in the given file') file = 'test.txt' with open(file, 'r') as f: ident = findLineParam("ID", f.read()) 运行它:

test.txt

它将返回<ID= 'foo' > <div></div> asdfnewnaf

答案 1 :(得分:0)

如果函数必须返回某些内容,则应返回一个默认值(仅在if语句上返回,因此,如果与if不匹配,则返回None) 我知道这并不能解决您的问题,但是最好得到这个^^

答案 2 :(得分:0)

正如@NoxFly建议的那样,所有路径都不会返回。

def findLineParam(sprotParam, pos, line):
    ret = ''
    if line[:2] == sprotParam:
        start = pos
        while line[start] == " ":
            start += 1
        stop = start + 1 
        while stop < len(line) and not line[stop] in (" ", ";"):
            stop += 1
        print(line[start:stop]) # prints the correct value!
        ret = line[start:stop] # returns None? 
   return ret

with open(file, 'r') as infile:
    for line in infile:
        ident = findLineParam("ID", 2, line)

更好的方法是使用正则表达式而不是while循环。 例如,正则表达式将找到该值。

r"ID:([^(\s|;)]*)"