命令行python上没有输出

2024-10-01 07:18:08 发布

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

这是我的密码。当我运行它时,它只是在运行后退出。什么都没有印出来。为什么?在

def checkString(filename, string):
    input = file(filename) # read only will be default file permission
    found = False
    searchString = string
    for line in input:
        if searchString in line:
            found = True
            break

if callfunc == 'initialize':
    print listdir() #this will print list of files
    print "\n"

for files in listdir():
    checkString(files,"hello")

if found:
    print "String found"
else:
    print "String not found"
input.close()

Tags: inforinputstringiflinefilesfilename
2条回答

found是函数checkString()中的一个local名称;它保持本地名称,因为您不返回它。在

从函数返回变量并存储返回值:

def checkString(filename, string):
    input = file(filename) # read only will be default file permission
    found = False
    searchString = string
    for line in input:
        if searchString in line:
            found = True
            break
    return found

for files in listdir():
    found = checkString(files,"hello")
    if found:
        print "String found"
    else:
        print "String not found"

您需要修改为:

def checkString(filename, string):
    input = file(filename) # read only will be default file permission
    found = False
    searchString = string
    for line in input:
        if searchString in line:
            found = True
            break

    input.close()
    return found

found = False

if callfunc == 'initialize':
    print listdir() #this will print list of files
    print "\n"

for files in listdir():
    found = found or checkString(files,"hello")

if found:
    print "String found"
else:
    print "String not found"

这是因为在原来的found只在函数checkString的作用域内

相关问题 更多 >