简体   繁体   中英

No output on command line python

This is my code. when I run it, it simply exits after running. There is nothing printed. Why so ?

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()

found is a local name in the function checkString() ; it stays local because you don't return it.

Return the variable from the function and store the return value:

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"

You need to modify to:

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"

This is because in your original found is only in scope within the function checkString

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM